Why does this line of unit test code work? groovy.sql.Sql doesn't have a no argument constructor.
Sql.metaClass.constructor = { dataSource -> return new Sql(); }
That line is amongst some others in a grails app which mocks out a Sql object's constructor and one of its methods. It works great.
Looking at the API for the Sql object, I do not see a no argument constructor: http://groovy.codehaus.org/api/groovy/sql/Sql.html
This style of overriding the constructor using Sql.metaClass.constructor is something I found at:
http://manuel-palacio.blogspot.com/2010/07/groovy-tip-metaprogramming-1.html
Thanks!
groovy.sql.Sql has no public no-args constructor, but as can be seen in the source, it does have a private no-args constructor -- I guess in order to support the syntax new Sql(connection: connection)?.
I'm kind of surprised, though, that that technique for stubbing doesn't generate an exception, e.g., when running sql.execute or the like.
Related
In Java, we can create an utilities class like this:
final class Utils {
public static boolean foo() {
return false;
}
}
But how to do this in Kotlin?
I try using functions inside object:
object Utils {
fun foo(): Boolean {
return false
}
}
But when call this method from Java code it need to add INSTANCE. Ex: Utils.INSTANCE.foo().
Then I change to declare it as top-level function (without class or object):
#file:JvmName("Utils")
#file:JvmMultifileClass
fun foo(): Boolean {
return true
}
Then I can call Utils.foo() from Java code. But from Kotlin code I got Unresolved reference compiler error. It only allow be to use foo() function directly (without Utils prefix).
So what is the best approach for declaring utils class in Kotlin?
The last solution you've proposed is actually quite idiomatic in Kotlin - there's no need to scope your function inside anything, top level functions are just fine to use for utilities, in fact, that's what most of the standard library consists of.
You've used the #JvmName annotation the right way too, that's exactly how you're supposed to make these top level functions easily callable for Java users.
Note that you only need #JvmMultifileClass if you are putting your top level functions in different files but still want them to end up grouped in the same class file (again, only for Java users). If you only have one file, or you're giving different names per file, you don't need this annotation.
If for some reason you want the same Utils.foo() syntax in both Java and Kotlin, the solution with an object and then #JvmStatic per method is the way to do that, as already shown by #marianosimone in this answer.
You'd need to use #JvmStatic for that:
In Kotlin:
object Utils {
#JvmStatic
fun foo(): Boolean = true
}
val test = Utils.foo()
In Java:
final boolean test = Utils.foo()
Note that the util class you used in Java was the only way to supply additional functions there, for anything that did not belong to a particular type or object. Using object for that in Kotlin does not make any sense. It isn't a singleton, right?
The second approach you mentioned is rather the way to go for utility functions. Internally such functions get translated to static ones and as you can see they become the static util classes in Java you are searching for, as you can't have standalone functions in Java without a class or enum. In Kotlin itself however they are just functions.
Some even count utility classes to the anti-patterns. Functions on the other hand make totally sense without a class or object whose name hasn't so much meaning anyway.
I'm a beginner of Kotlin, there are many omitted code with Kotlin. It make me crash when I read some sample code.
Such as var map=HashMap()
I can't judge what HashMap() is function or class. I have to judge it by Hint of Android Studio. Do you have a simple way?
If I use java, it will be different code style.
Function: Map map=myFunction()
Class: Class myClass=new Class()
First, if you follow Java naming conversion, class is PascalCase and function is camelCase.
Second, it does not matter. Creating a new object is just a constructor returning an object. It does not different from a a function return an object.
I can't judge what HashMap() is function or class
Don't think of this as class or function. HashMap() is a constructor which is really a method (function) that returns an instance of an object. So there is really no need of the new keyword here, and it make for clean code.
You can identify if it's a function or a constructor based on the Name itself (the case of the name).
I'm completely new to JMockIt. In the tutorial I see example codes that uses the final modifier for a #Mocked parameter e.g.
#Test
public void doSomethingHandlesSomeCheckedException(#Mocked final DependencyAbc abc) throws Exception
{
...
}
What does final mocked parameter mean here? Sometimes, "final" is not used. What is the difference?
This is merely a Java language issue, nothing to do with JMockit itself. For a method parameter or local variable to be used inside an inner class (anonymous or not), the Java compiler requires it to be declared as final.
From the JMockit tutorial:
"For a mock parameter declared in a test method, an instance of the declared type will be automatically created by JMockit and passed by the JUnit/TestNG test runner when calling the test method. Therefore, the parameter value will never be null.
For a mock field, an instance of the declared type will be automatically created by JMockit and assigned to the field, unless it's a final field. In such case, a value should be created and assigned to the field explicitly in test code. This value can be null, though, which is perfectly valid for a mocked class if only constructors and static methods are going to be called on it."
http://jmockit.googlecode.com/svn/trunk/www/tutorial/BehaviorBasedTesting.html#declaration
Keep in mind that a mock parameter/field is any annotated with #Mocked or #Injectable.
A method can be tested either with mock object or without. I prefer the solution without mock when they are not necessary because:
They make tests more difficult to understand.
After refactoring it is a pain to fix junit tests if they have been implemented with mocks.
But I would like to ask your opinion. Here the method under test:
public class OndemandBuilder {
....
private LinksBuilder linksBuilder;
....
public OndemandBuilder buildLink(String pid) {
broadcastOfBuilder = new LinksBuilder(pipsBeanFactory);
broadcastOfBuilder.type(XXX).pid(pid);
return this;
}
Test with mocks:
#Test
public void testbuildLink() throws Exception {
String type = "XXX";
String pid = "test_pid";
LinksBuilder linkBuilder = mock(LinksBuilder.class);
given(linkBuilder.type(type)).willReturn(linkBuilder);
//builderFactory replace the new call in order to mock it
given(builderFactory.createLinksBuilder(pipsBeanFactory)).willReturn(linkBuilder);
OndemandBuilder returnedBuilder = builder.buildLink(pid);
assertEquals(builder, returnedBuilder); //they point to the same obj
verify(linkBuilder, times(1)).type(type);
verify(linkBuilder, times(1)).pid(pid);
verifyNoMoreInteractions(linkBuilder);
}
The returnedBuilder obj within the method buildLink is 'this' that means that builder and returnedBuilder can't be different because they point to the same object in memory so the assertEquals is not really testing that it contains the expected field set by the method buildLink (which is the pid).
I have changed that test as below, without using mocks. The below test asserts what we want to test which is that the builder contains a LinkBuilder not null and the LinkBuilder pid is the one expected.
#Test
public void testbuildLink() throws Exception {
String pid = "test_pid";
OndemandBuilder returnedBuilder = builder.buildLink(pid);
assertNotNull(returnedBuilder.getLinkBuilder());
assertEquals(pid, returnedBuilder.getLinkBuilder().getPid());
}
I wouldn't use mock unless they are necessary, but I wonder if this makes sense or I misunderstand the mock way of testing.
Mocking is a very powerful tool when writing unit tests, in a nut shell where you have dependencies between classes, and you want to test one class that depends on another, you can use mock objects to limit the scope of your tests so that you are only testing the code in the class that you want to test, and not those classes it depends on. There is no point me explaining further, I would highly recommend you read the brilliant Martin Fowler work Mocks Aren't Stubs for a full introduction into the topic.
In your example, the test without mocks is definitely cleaner, but you will notice that your test exercises code in both the OndemandBuilder and LinksBuilder classes. It may be that this is what you want to do, but the 'problem' here is that should the test fail, it could be due to issues in either of those two classes. In your case, because the code in OndemandBuilder.buildLink is minimal, I would say your approach is OK. However, if the logic in this function was more complex, then I would suggest that you would want to unit test this method in a way that didn't depend on the behavior of the LinksBuilder.type method. This is where mock objects can help you.
Lets say we do want to test OndemandBuilder.buildLink independent of the LinksBuilder implementation. To do this, we want to be able to replace the linksBuilder object in OndemandBuilder with a mock object - by doing this we can precisely control what is returned by calls to this mock object, breaking the dependency on the implementation of LinksBuilder. This is where the technique Dependency Injection can help you - the example below shows how we could modify OndemandBuilder to allow linksBuilder to be replaced with a mock object (by injecting the dependency in the constructor):
public class OndemandBuilder {
....
private LinksBuilder linksBuilder;
....
public class OndemandBuilder(LinksBuilder linksBuilder) {
this.linksBuilder = linksBuilder;
}
public OndemandBuilder buildLink(String pid) {
broadcastOfBuilder = new LinksBuilder(pipsBeanFactory);
broadcastOfBuilder.type(XXX).pid(pid);
return this;
}
}
Now, in your test, when you create your OndemandBuilder object, you can create a mock version of LinksBuilder, pass it into the constructor, and control how this behaves for the purpose of your test. By using mock objects and dependency injection, you can now properly unit test OndemandBuilder independent of the LinksBuilder implementation.
Hope this helps.
It all dependent upon what you understand by UNIT testing.
Because when you are trying to unit test a class , it means you are not worried about the underlying system/interface. You are assuming they are working correctly hence you just mock them. And when i say you are ASSUMING means you are unit testing the underlying interface separately.
So when you are writing your JUnits without mocks essentially you are doing a system or an integration test.
But to answer your question both ways have their advantages/disadvantages and ideally a system should have both.
I'm fairly new to Ninject, but I have successfully managed to use it for DI using a custom provider.
The binding is initialised as follows
kernel = new StandardKernel();
kernel.Bind<IPatientRecordLocator>().ToProvider<PatientRecordLocatorProvider>();
and in the custom provider I call Activator.CreateInstance like so
protected override IPatientRecordLocator CreateInstance(IContext context)
{
var name = ConfigurationManager.AppSettings["PatientRecordLocator"];
var typeName = name.Split(',')[0];
var assemblyName = name.Split(',')[1];
return Activator.CreateInstance(assemblyName, typeName).Unwrap() as IPatientRecordLocator;
}
(yes, I am aware that there is no error handling, etc. in the code above :) )
and all this works like a charm.
Now, the problem I'm facing is when I introduce a new class that I wish to inject into instances of IPatientRecordLocator. The problem occurs when I add a constructor like the following to e.g. one of these classes
[Inject]
public MockPatientRecordLocator (IContactAdapter contactAdapter)
{
...
}
Then, for Activator.CreateInstance to work I also have to add a parameterless constructor to class MockPatientRecordLocator, i.e.
public MockPatientRecordLocator()
{
}
So, my question is: how can I make Ninject inject an instance of a class that implements IContactAdapter into e.g. MockPatientRecordLocator? I've tried method injection, but to no avail.
I forgot to explain that what I'm trying to achieve is a kind of chained injection where an instance of class PatientRecordSummary gets injected with an instance of MockPatientRecordLocator (using constructor injection) and said instance of MockPatientRecordLocator should get injected with an instance of IContactAdapter (again using constructor injection (if possible)). The first part of the chain works, the second doesn't.
Not bad for a first question!
You want to use the Bind(Type) overload to allow registration of stuff that you dont have statically available in the context of your Load() code - do the stuff you're doing in your provider (i.e., resolving the Type) up-front. This will allow Ninject to do the object instantiation (without any requirement for a default .ctor)
IIRC two or 3 of my most recent answers also touch on this discovery/loading stuff, and have examples that should be relevant to your case.
(And you wont need to resort to [Inject] attributes when you've gotten to remove things)