Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito - when thenReturn

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?

like image 523
Paz Avatar asked Jul 20 '17 18:07

Paz


People also ask

What is the use of when thenReturn in Mockito?

The thenReturn() methods lets you define the return value when a particular method of the mocked object is been called.

How do you mock method which returns void?

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.

What is the use of Mockito when?

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.

What is lenient () Mockito?

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.


1 Answers

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));
like image 126
Mureinik Avatar answered Sep 22 '22 11:09

Mureinik