I have this very simple example as follows:
public class Foo {
public int foo() {
return foo1();
}
public int foo1() {
return 1;
}
}
public class FooTest {
#Test public void testFoo() {
Foo f = mock(Foo.class);
doReturn(1000).when(f).foo1();
assertThat(f.foo(), equalTo(1000));
}
}
I'm getting a java.lang.AssertionError: Expected: is(1000) got: <0>, and I don't understand why. Obviously I must be doing something wrong, as this is very basic mocking, so I can't imagine this doesn't work.
Note that you recorded the expectation on foo1(), but then called foo() later... So of course, it returns 0, not 1000.
What you need is a spy instead of a mock.
http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#13
Try this
Foo foo = new Foo();
Foo f = spy(foo);
By the time CGLIB has gotten hold of your Foo class it doesn't care about what clever implementation you have underlying. Your return statement is not considered. Mockito sees (1) a mocked class called Foo, (2) an instruction when foo1() is invoked and (3) no instructions when foo() is invoked.
On a stylistic note isn't when preferred over doReturn now? So;
when(f.foo1()).thenReturn(1000);
Related
I am trying to use call operator () overloading, but it does not work on class fields. What's wrong?
class Foo {
void call(int x){
println("x="+x)
}
}
class MyCallable {
Foo foo = new Foo()
}
Foo foo = new Foo()
foo(5) //works
MyCallable mc = new MyCallable()
mc.foo(2) //not works
But program terminated with exception:
Exception in thread "main" groovy.lang.MissingMethodException: No
signature of method: mpctests.MyCallable.foo() is applicable for
argument types: (java.lang.Integer) values: [2]
You get MissingMethodException when you call mc.foo(5), because Groovy's invoke object method mechanism gets triggered. There is one thing worth explaining to get a better understanding about this situation. Your MyCallable class:
class MyCallable {
Foo foo = new Foo()
}
gets compiled to something like this:
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
public class MyCallable implements GroovyObject {
private Foo foo;
public MyCallable() {
CallSite[] var1 = $getCallSiteArray();
Object var2 = var1[0].callConstructor(Foo.class);
this.foo = (Foo)ScriptBytecodeAdapter.castToType(var2, Foo.class);
MetaClass var3 = this.$getStaticMetaClass();
this.metaClass = var3;
}
public Foo getFoo() {
return this.foo;
}
public void setFoo(Foo var1) {
this.foo = var1;
}
}
Groovy also compiles every field access like mc.foo to a getter method call mc.getFoo(). So when you call mc.foo(5) it is clear for Groovy runtime that you expect to call a foo(5) method on mc object. And this method does not exist and MissingMethodException gets thrown.
However, it works if you create object def foo = new Foo() and then you call foo(5), because foo is an object and foo(5) is a strict instruction to invoke call(5) method on foo object (foo(5) is a shorthand version of foo.call(5)). The same situation would take place if you call mc() - Groovy would try to invoke mc.call() method. But when you say mc.foo(5) it's clear that you are trying to invoke foo(5) method.
If you want to use call operator on mc.foo field there are two options:
1. Use direct field access operator #
mc.#foo(5)
In this case you refer directly to foo field and you can use shorthand call operator.
2. Use with {} method
mc.with {
foo(5)
}
In this case it is also a straightforward for Groovy runtime that you are accessing foo field and you can use call operator on it.
Alternatives
Using getter method:
mc.getFoo()(5)
Using method call() directly:
mc.foo.call(5) // equivalent of mc.getFoo().call(5)
Ideally I'd like to be able to express the idea: "whatever would be called by foo() in the current position in the code, give me a method reference to foo".
Rationale: I'm working on some code that uses a lot of high-order functions and function composition. I'd like: a) it to be as terse as possible, and b) not to have to
keep editing class names scattered around the code as I refactor and move functions between classes.
For example:
/* ---- foo.pkg1.Utils.groovy */
public final class Utils {
private Utils() { /* as it's all static methods */ }
static foo() { 42; }
}
/* ---- foo.pkg2.Client1.groovy */
import foo.pkg1.Utils
def f1 = Utils.&foo // <-- restates class (but works)
println f1()
/* ---- foo.pkg2.Client2.groovy */
import static foo.pkg1.Utils.*
def f2 = foo // <-- No!
// "groovy.lang.MissingPropertyException: No such property: foo ..."
println f2()
def f3 = &foo // <-- No!
// "unexpected token: & at line: 17, column: 14"
println f3()
def f4 = this.&foo // <-- Also no!
// "groovy.lang.MissingMethodException: No signature of method..."
println f4()
/* ---- foo.pkg2.Client3.groovy */
/* My best attempt ... but this only allows me to change which
class 'u' refers too, not to create a method reference to
whatever `foo()` would call at the same place in the code. */
import static Utils as u
def f5 = u.&foo
println f5()
Slightly error-prone due to variable naming being bounded to with order, but it is something:
class Util {
static foo(arg) { "foo $arg" }
static bar() { "bar" }
static batman(fn) { fn("captain") }
}
def (foo, bar, batman) = Util.with { [it.&foo, it.&bar, it.&batman] }
assert foo("eck") == "foo eck"
assert batman(foo) == "foo captain"
Handling the script's own binding using reflection on Util class is also an option if you always use scripts.
You can have the MethodClosure defined as a private static property of the class Utils like:
import org.codehaus.groovy.runtime.MethodClosure
public final class Utils {
private static final MethodClosure fooPointer = this.&foo
private Utils() { }
static foo() { 42 }
}
// Client
import static Utils.*
def f1 = fooPointer
println f1()
Do not know how will it be advantageous anyway.
Here's my case, I have a class A which has one member field b. And I want to test and in unit test, I mocked A and also need to call method f() which will invoke b's f(). But the b variable in mocked A is null, so will throw NPE, and I have no get/set method for b, so is there any way to mock b ? THanks
public static class B{
public void f() {
}
}
public static class A {
B b;
public void f() {
b.f();
}
}
If you want to mock out the b property of A in a test, you've given the b property default (package-private) access, so as long as your test is in the same package you could replace the b property directly.
#Test
public void testB() {
A underTest = new A();
B mockedB = Mockito.mock(B.class);
underTest.b = mockedB;
underTest.f();
Mockito.verify(mockedB).f();
}
As an aside, I personally dislike using package-private access to mess around with member properties for tests, and instead would recommend a dependency injection framework like Guice or Spring DI for constructor injection.
However you've described that you've mocked out A, I'd have thought if this was the case the f() method of A would do nothing - you wouldn't get a null pointer exception as the call to the mock will replace the real b property and just be a void method that does nothing. Please can you provide more details if this is the case?
I have some Groovy class, for example:
class Apple {
public void methodA(String myParam) {}
public void methodB(String myParam2, String myParam3) {}
}
And I want to print all methods of class Apple in convenient format, for example:
Class Apple:
- methodA <String: myParam>
- methodB <String: myParam2> <String: myParam3>
or just:
Class Apple:
- methodA <myParam>
- methodB <myParam2> <myParam3>
Is it possible in Groovy?
For now I'm using for-each loop for Apple.metaClass.methods and printing method.name, for example:
for (MetaMethod metaMethod in Apple.metaClass.methods) {
println metaMethod.name
}
But I can't find a way to print names of arguments..
Also, is it possible to know if there are default values for the arguments?
Could you please advise?
No(*). Parameter names are not stored with the bytecode (I believe they might be if the class is compiled with debugging turned on, but I've not tried it).
(* it is possible with some non-reflection digging, but it relies on a lot of things, and feels like it would be quite a brittle point in your design)
With Java 7 and below, you can just get the types of the arguments. With Java 8, a new getParameters call was added to java.lang.reflect.Method, so with Java 8 and Groovy 2.3+ it's possible to do:
class Apple {
public void methodA(String myParam) {}
public void methodB(String myParam2, String myParam3) {}
}
Apple.class.declaredMethods
.findAll { !it.synthetic }
.each { println "$it.name $it.parameters.name" }
To print:
methodB : [arg0, arg1]
methodA : [arg0]
But as you can see, the original parameter names are again lost.
As for default values, the way Groovy handles these is to create multiple methods. If you declare a method:
class Apple {
public void foo( bar="quux" ) { println bar }
}
Then this generates two methods in bytecode:
public void foo() { foo( 'quux' ) }
public void foo( bar ) { println bar }
If you run the above method inspector for this class containing the method foo, you'll see the output is:
foo : [arg0]
foo : []
I have several classes all implementing an interface IBar. Those classes are BarA, BarB, BarC.
I also have a base class Foo:
abstract class Foo
{
void Do(IBar bar)
{
Handle((dynamic)bar);
}
void Handle(IBar bar)
{
Console.Out.WriteLine("Fallback Scenario");
}
}
I want a child class FooChild like follows:
class FooChild : Foo
{
void Handle(BarA bar) {
Console.Out.WriteLine("Handling BarA");
}
void Handle(BarB bar) {
Console.Out.WriteLine("Handling Bar");
}
}
No I want to do the following, but I don't get the result I expect
var foo = new FooChild();
foo.Handle(new BarA()); // expected: Handling BarA, actual: Fallback Scenario
foo.Handle(new BarB()); // expected: Handling BarB, actual: Fallback Scenario
foo.Handle(new BarC()); // expected: Fallback Scenario, actual: Fallback Scenario
I can solve it by moving the Do(IBar bar) method to the FooChild class, but I don't want to do that. I might have 10 Foo childs and don't want to repeat that code. Is there a solution for this?
I think you want this:
void Do(IBar bar)
{
dynamic dynamicThis = this;
dynamicThis.Handle((dynamic) bar);
}
That way the method will be found against the actual type of this. Otherwise, the compiler remembers that the method was called from Foo, and only treats the argument dynamically, finding methods which would have been available from Foo with the actual type of bar. You want methods which would have been available from the actual type of this, as well as using the actual type of bar (via the cast to dynamic).
(You'll need to make the Handle methods public though.)