简体   繁体   中英

Mockito.mock is not working, using Mockito.when causes NullPointerException

I have used Mockito very long time. With Mockito 4.7.0 version (and also for example with the version 3.12.4) the code:

A a = mock(A.class);
when(a.doX()).thenReturn("X");

causes the java.lang.NullPointerException in the second line.

When I print the content of the variable a

System.out.println(a);

I got also "java.lang.NullPointerException".

For any other class the Mockito.mock and Mockito.when are working perfectly and if I print a content of some other class instance b I got "Mock for B, hashcode: some hash code"

Do you know what could be problem? My example is simplified and I can't show the actual classes.

I don't have your code, but I tried to be the more generic as I can. I have test like the one below and it works great. Hope to been helpful.

@ExtendWith(MockitoExtension.class)
class MyTest {

    @Mock
    private AClass aclass;

    @Mock
    private BClass bclass;

    @Mock
    private CClass cclass;

    @Test
    void testExecute() {
        
        when(aclass.getAbc(any(String.class), any(Date.class), anyString()))
            .thenAnswer(i -> getAbc(i.getArgument(0), i.getArgument(1), i.getArgument(2)));

        when(bclass.isOk())
            .thenAnswer(i -> false);

        when(cclass.getCdf(anyString()))
            .thenAnswer(i -> getCdf());
        ...
        ...
        ...

    }

    private List<ABC> getAbc(final String myString, final Date now, final String x) {
        ...
        ...
        ...
    }

    private CDF getCdf() {
        ...
        ...
        ...
    }

}

As you can see, for a simple answer I write the answer directly, for a more complex one, I create a private method with the same name and use it as answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM