I am using Mockito to mock a certain class while writing my test cases.
Is there a way to print some statements before returning a value? Like:
when(x.callFunction(10).thenReturn(new String("Hello"));
The above statement works, however I am not able to do the following:
when(x.callFunction(10).thenReturn({
System.out.println("Mock called---going to return hello");
return new String("Hello");});
thenReturn or doReturn() are used to specify a value to be returned upon method invocation. //”do something when this mock's method is called with the following arguments” doReturn("a").
One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test. I strongly recommend only using doReturn/when .
Mockito @Mock Annotation We can mock an object using @Mock annotation too. It's useful when we want to use the mocked object at multiple places because we avoid calling mock() method multiple times. The code becomes more readable and we can specify mock object name that will be useful in case of errors.
Mockito verify() simple example It's the same as calling with times(1) argument with verify method. verify(mockList, times(1)). size(); If we want to make sure a method is called but we don't care about the argument, then we can use ArgumentMatchers with verify method.
With thenAnswer
you can execute additional actions every time the mocked method is invoked.
when(x.callFunction(10)).thenAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) {
System.out.println("Mock called---going to return hello");
return "Hello";
}
});
See also thenAnswer Vs thenReturn.
If the object you're going to create is not final
, then besides thenAnswer
provided by @Roland Weisleder, you can just use an anonymous subclass with init block in thenReturn
, like the following example code:
class FoobarFactory {
public Foobar buildFoobar() {
return null;
}
}
class Foobar {
private String name;
public Foobar(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
with mock code as:
@Test
public void testFoobar() throws Exception {
FoobarFactory foobarFactory = mock(FoobarFactory.class);
when(foobarFactory.buildFoobar()).thenReturn(new Foobar("somename") {
{
System.out.println("Creating mocked Foobar");
}
});
Foobar foobar = foobarFactory.buildFoobar();
assertThat(foobar.getName(), is("somename"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With