javamockitostub

Force Mockito to return null instead of emtpy list


I have a simple test with mocked Properties class:

@RunWith(MockitoJUnitRunner.class)
public class MockitoReturnListTest {
    @Mock
    Properties myProperties;
    
    @Test
    public void propertiesTest() {
        Set<String> propertyNames = myProperties.stringPropertyNames();
        System.out.println(propertyNames);
    }
}

I have not created any stubbing for stringPropertyNames method, yet Mockito is returning an empty set when I call it. The output of the test is:

[]

How can I instruct Mockito to return null for all methods instead of empty collection? (In reality I have much bigger class with many List<> getSomething() methods, which I wish to return null)

I know I could stub the method like that:

    @Test
    public void propertiesTest2() {
        Set<String> propertyNames = myProperties.stringPropertyNames();
        when(myProperties.stringPropertyNames()).thenReturn(null);
        System.out.println(propertyNames);
    }

But I would like to make some sort of automatic stubbing for all methods to return null be default.


Solution

  • Write your own Answer class that overrides the answer method to always return null. It's a functional interface, so you can write it succinctly using a lambda.

    Then, to use this Answer class for your mocked class, use the mock method instead of the @Mock annotation:

    Answer<Object> myAnswer = (invocation) -> null;
    Properties myProperties = mock(Properties.class, myAnswer);
    

    If you want this answer to be the default for all mocks, change your default Mockito configuration by creating a class in your CLASSPATH called org.mockito.configuration.MockitoConfiguration (see doc for details). Make sure you define it in the org.mockito.configuration package and that its name is MockitoConfiguration.

    In your MockitoConfiguration class, override the getDefaultAnswer() method to return your own Answer object.