简体   繁体   中英

NullPointerException when calling method of a mocked class

When I am running a unit test for below class, I am getting NullPointerException where indicated by the comments. I have a feeling that I am missing something simple here. I am using Mockito 1.9.5 and none of the mocked methods are final.

public class UserBOTest {

    @Mock private IUserDAO userDao;

    @InjectMocks private IUserBO userBo = new UserBO();

    @Test
    public void testRegister() throws DBException {
        when(userDao.doesEmailExist(any(String.class))).thenReturn(false); //NULLPOINTEREXCEPTION HERE
        when(userDao.saveOrUpdate(Matchers.<User>any())).thenReturn(true);
        Assert.assertEquals(userBo.registerUser("user", "pwd", "email", ""), Constants.General.OK);
    }

}

Stack trace:

java.lang.NullPointerException
    at com.dbcreator.services.bo.UserBOTest.testRegister(UserBOTest.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

Your userDao is null. You need to tell Mockito to actually inject the mocks declared in the test by doing

@Before
public void prepare() {
    MockitoAnnotations.initMocks(this);
}

Remember that annotations are only metadata. They don't do anything. A tool can use them to do something thanks to them. In this case, this tool is MockitoAnnotations.initMocks() , which reads the fields of the test object, inspect annotations, and creates/inject mocks.

Since it appears your mock object itself is null, I'm guessing you're missing some initialization.

In order to use the @Mock annotation, you need somewhere in your test or in your test runner, you need to have a call that initializes the mock annotations:

MockitoAnnotations.initMocks(testClass);

If you use a MockitoJUnitRunner this should be done for you.

Your userDao is likely null because you are missing the following:

 MockitoAnnotations.initMocks(this);

The above call it required for the @Mock annotation to work. See: http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#9

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