I'm trying to get to grips with EasyMock to mock some calls to Jersey client APIs...
I'm trying to mock a call to the following call Builder API:
<T> T post(Entity<?> entity, Class<T> responseType);
doing the following:
EasyMock.expect(mockInvocationBuilder.post(Entity.json(request), Response.class)).andReturn(mockResponse).anyTimes();
this is giving me the following error:
java.lang.AssertionError:
Unexpected method call Builder.post(Entity{entity=com.ibm.apin.apim.request.CreateOrgRequest#936a7073, variant=Variant[mediaType=application/json, language=null, encoding=null], annotations=[]}, class javax.ws.rs.core.Response):
Can anyone see what I'm doing wrong here and how I can mock this correctly?
See EasyMock User Guide:
To match an actual method call on the Mock Object with an expectation, Object arguments are by default compared with equals().
You have to override equals(), use a built-in argument matcher (like EasyMock#anyObject), write your own IArgumentMatcher or use a Capture.
Related
My question, which was similar to this:
Using mockito; is it possible to mock a method that takes a lambda as a parameter and assert variables captured by the lambda?
But different enough that I still had take a while to figure it out was:
How do I verify that a method called by a mock that was used inside a lambda that was passed to a method of another mock object?
This may seem convoluted, but it happens a lot with Java 8 libraries like JDBI, for example, you have a JDBI object:
JDBI MyDBConnection
That you should mock. And then that is used with the withHandle method to pass a lambda implementing the HandleCallback<R,X> type:
//code I'm testing. I implement the lambda, and want to verify it
//calls the correct method in dao provided by JDBI.
MyDBConnection.withHandle(
(handle) -> { ... handle.attach(SomeDao.class).findSomethingInDB(args) .. }
Which is the recommended way to do this.
So I want to verify that findSomethingInDB(eq(args)) is called.
Like I said this was similar, but different enough, that, I at least, will find this answer valuable at some future point, when I forget how to do this. So the original 3rd party library method that invokes my lambda is processed similar to the answer given in the question referenced above, but with some tweaks:
when(JDBIMock.withHandle(any())).then(
//Answer<Void> lambda
invocationOnMock -> {
Object[] args = invocationOnMock.getArguments();
assertEquals(1, args.length);
//the interface def for the callback passed to JDBI
HandleCallback lambda = (HandleCallback) args[0];
when(mockHandle.attach(SomeDao.class)).thenReturn(mockDao);
//this actually invokes my lambda, which implements the JDBI interface, with a mock argument
lambda.withHandle(mockHandle);
//bingo!
verify(mockDao).findSomethingInDB(eq(args));
}
)
See the question, it should be answered sufficiently above ;)
I am trying to do something very similar with verifying the arguments passed to another mock from withHandle on a mock JDBI call in a test.
The answer you give in the question pointed me in the right direction but gives me the error message:
The method then(Answer<?>) in the type OngoingStubbing<Object> is not applicable for the arguments ((<no type> invocationOnMock) -> {})
Instead I had to use a new org.mockito.stubbing.Answer passed to the then, similar to in the other question you linked to.
In your example this would be something like:
when(JDBIMock.withHandle(any())).then(
//Answer<Void> lambda
new Answer<Void>() {
#Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
assertEquals(1, args.length);
//the interface def for the callback passed to JDBI
HandleCallback lambda = (HandleCallback) args[0];
when(mockHandle.attach(SomeDao.class)).thenReturn(mockDao);
//this actually invokes my lambda, which implements the JDBI interface, with a mock argument
lambda.withHandle(mockHandle);
//bingo!
verify(mockDao).findSomethingInDB(eq(args));
return null; // to match the Void type
}
}
)
In my case I was expecting a result list from withHandle so I had to change the Answer type, and return type of answer to match and return a dummy list instead of Void. (The actual results returned didn't matter in this test, only that the expected arguments were passed to my subsequent mock object).
I also moved the verify call outside of the Answer into the main body of my test so it was clearer this was the expectation of the test, not part of the mocking setup.
as the title suggests, the problem is this: I have the mock of AdesioneMerger and I have to call the real merge method. merge is a void method.
This is wrong:
adesioneMerger = Mockito.spy(AdesioneMerger.class);
Mockito.when(adesioneMerger.merge(
Matchers.any(AdesioneBean.class),
Matchers.any(Adesione.class),
Matchers.any(ServiceResultBean.class))
).ThenCallRealMethod();
what's the error?
For void methods, use the alternative API:
Mockito.doCallRealMethod()
.when(adesioneMerger).merge(
Matchers.any(AdesioneBean.class),
Matchers.any(Adesione.class),
Matchers.any(ServiceResultBean.class));
The problem is that Mockito.when() requires an argument (and there are no void-typed arguments in Java). The alternative API works around this by calling when() on the mock type and the actual method to mock is called on the return value of when(...).
See also this answer: How to make mock to void methods with mockito
try this way:
doCallRealMethod().when(adesioneMerger).merge(
Matchers.any(AdesioneBean.class),
Matchers.any(Adesione.class),
Matchers.any(ServiceResultBean.class);
My actual method signature is:
public List<T> readFileToMemory(FooFile fooFile, **Class<T> entityClass**) { }
and I am trying to mock this as:
when(mockObject.readFileToMemory(any(FooFile.class),
Matchers.any(Class<Bar>)).thenReturn(new ArrayList<Bar>())
but second argument doesn't compile. How to fix it?
I referred to the following answers but still no luck.
Mockito: List Matchers with generics
Mockito: Verifying with generic parameters
Oh i fixed it as:
when(mockObject.readFileToMemory(any(FooFile.class),
Matchers.<Class<Bar>>any())).thenReturn(new ArrayList<Bar>())
You could also get it working with:
when(mockObject.readFileToMemory(any(FooFile.class), eq(Bar.class)))
.thenReturn(new ArrayList<Bar>());
I have this method, "instance" is #Mock
instance.lookup(
SomeClass.class.getField("field").getAnnotation(MyAnnotation.class),
Annotation... annotations
)
Signature of that method is exactly this:
Object lookup(MyAnnotation resource, Annotation... annotations);
Now, that Annotation... value is put there on that mock in runtime in the code I test.
I am trying to Mock it so when I do
Mockito.when(instance.lookup....).thenReturn(something);
but lookup method always returns null value and exception it thrown (it basically do not return "something" but null)
I was thinking that I have to mock these varargs as well so I modified it to this
Mockito.when(instance.lookup(_instance line_, Mockito.any(Annotation[].class)))
but it fails telling me that I am using it "raw".
When I use anyVarargs() like this
Mockito.when(instance.lookup(_that line_, Mockito.anyVararg()))
Mockito.anyVararg() returns Object but I need Annotation[]
Any hint here?
Thanks a lot!
How can I capture (for assertion purposes) the parmeters passed to a static stub method call?
The methodBeingStubbed looks like this...
public class SomeStaticClass{
protected static String methodBeingStubbed(Properties props){
...
I am stubbing the method call because it i need to verify that it gets called...
PowerMockito.stub(PowerMockito.method(SomeStaticClass.class, "methodBeingStubbed")).toReturn(null);
PowerMockito.verifyStatic();
But I now also want to know what properties were passed to this "methodBeingStubbed" and assert it is as expected
After the call to verifyStatic, you'll need to actually call the method you're trying to verify, as in the documentation here:
PowerMockito.verifyStatic(Static.class);
Static.thirdStaticMethod(Mockito.anyInt());
At that point you can use Mockito argument captors, as demonstrated (but not tested):
ArgumentCaptor<Properties> propertiesCaptor =
ArgumentCaptor.forClass(Properties.class);
PowerMockito.verifyStatic(SomeStaticClass.class);
SomeStaticClass.methodBeingStubbed(propertiesCaptor.capture());
Properties passedInValue = propertiesCaptor.getValue();
If you're used to #Mock annotations, or you need to capture a generic (as in List<String>), you may also be interested in using the #Captor annotation instead.