Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Mockito - when thenReturn

Writer Sebastian Wright

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?

2

1 Answer

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));
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy