Mockito - when thenReturn

Paz :

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?

Mureinik :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=438466&siteId=1