I'm new to the Mockito library and I can't understand the following syntax: before the test I defined -
when(CLASS.FUNCTION(PARAMETERS)).thenReturn(RETURN_VALUE)
And the actual test is -
assertSame(RETURN_VALUE, CLASS.FUNCTION(PARAMETERS))
Don't I just set the return value of the function with the first line of code (when... thenReturn
) to be RETURN_VALUE
? If the answer is yes, then of course assertSame
will be true and the test will pass, what am I missing here?
The thenReturn() methods lets you define the return value when a particular method of the mocked object is been called.
Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.
Mockito is a mocking framework, JAVA-based library that is used for effective unit testing of JAVA applications. Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.
lenient() to enable the lenient stubbing on the add method of our mock list. Lenient stubs bypass “strict stubbing” validation rules. For example, when stubbing is declared as lenient, it won't be checked for potential stubbing problems, such as the unnecessary stubbing described earlier.
The point of Mockito (or any form of mocking, actually) isn't to mock the code you're checking, but to replace external dependencies with mocked code.
E.g., consider you have this trivial interface:
public interface ValueGenerator {
int getValue();
}
And this is your code that uses it:
public class Incrementor {
public int increment(ValueGenerator vg) {
return vg.getValue() + 1;
}
}
You want to test your Incrementor
logic without depending on any specific implementation of ValueGenerator
.
That's where Mockito comes into play:
// Mock the dependencies:
ValueGenerator vgMock = Mockito.mock(ValueGenerator.class);
when(vgMock.getValue()).thenReturn(7);
// Test your code:
Incrementor inc = new Incrementor();
assertEquals(8, inc.increment(vgMock));
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