3 basic mistakes for NullPointerException when Mock

You might get NullPointerException exception when you try to mock object in your tests. This article is a shortlist of the three most common reasons why this might be happening.

Here is a working example of DocumentRepositoryTest class for reference:

@RunWith(MockitoJUnitRunner.class)
public final class DocumentRepositoryTest {

    @Mock
    private DocumentRepository documentRepository;

    @Test
    public void testConvertToNewDocument() {
        String paperColor = new String("white");
        Mockito.when(this.documentRepository.getPaperColor()).thenReturn(paperColor);
        String color = this.documentRepository.getDocumentColor();
        Assert.assertThat(color, is(new String("white"));
    }
}

DocumentRepositoryTest class is mocking documentRepository object.

So you are running your test and suddenly you see NullPointerException:

java.lang.NullPointerException at com.your.custom.clazz.Method.insertTest(CustomServiceTest.java:50)

You looked it up, and it seems your test is written correctly. So what might be a problem if you know how the mocking works?

If you are sure by your mocking skills, the issue will be probably somewhere else. And most likely very trivial. Here is a list of 3 things you should check out.

1. Return something for your Mock.

Most likely, you mistyped returning function. You probably wanted to return the value for the mocked object. So instead of when-thenReturn , you might type just when-then. Maybe it was IntelliSense. Maybe you did it accidentally. But for sure, NullPointerException happened because you want something which is not there. Debug and check if you are returning something.

2. Specify Mockito running class

Don’t forget to annotate your Testing class with @RunWith(MockitoJUnitRunner.class). Most of the people just forget to specify the test runner, running class for mocking.

3. You need to annotate the mocking object with the @Mock annotation

If you want to mock an object, you need to annotate the object with @Mock annotation.

This entry was posted in Testing and tagged , , , . Bookmark the permalink.

5 Responses to 3 basic mistakes for NullPointerException when Mock

  1. Jagadeesh Uppalapati says:

    I fallowed above rules correctly.
    while doing Mock to Window geting null instance
    @Mock
    Window window;

  2. Pingback: Null pointer exception when stubbing – Ask Android Questions

  3. ajitha says:

    Followed ur steps well bt still facing the null pointer exceptions .
    in testing class it mocked object is mocking perfectly but when it goes to corresponding class that mocked reference is becoming null…

    plss help me to solve this

  4. ajith says:

    my code

    public class StockController{
    @Autowired
    private StockService stockService;

    public GatewayResponse findProduct(String productId) {
    try{
    Optional optional = stockService.getProduct(productId);
    if (optional.isPresent()) {
    Product product = optional.get();
    return new GatewayResponse(HttpStatus.Ok,product, Message.SUCCESS.getDesc());
    }
    return new GatewayResponse(HttpStatus.NO_CONTENT,product, Message.SUCCESS.getDesc());
    }
    catch(Exception e)
    {
    log.info(“bad product id……..”);
    }
    }

    ******************
    Test class

    @RunWith(MockitoJunitRunner.class)
    public void ControllerTest()
    {
    @InjectMocks
    StockController stockController;
    @Mock
    StockService stockService;
    @Test
    public void findProductTest()
    {
    String productId = “pr455”;
    Product pr = new Product();
    pr.setName(“buhbdf”);
    when(stockService.getProduct(productId)).thenReturn(Optional.of(product));
    MvcResults mvcResults = mockMvc.perform(get(“/product”).param(“id”, productId)).andExpect(Status().isOk()).andReturn();
    }

    NOTE: just exclude if any syntax exceptions it might be my typing mistakes. every thing is fine just getting NullpointerException. i declared MockMvc object also bt didn’t mension here

    when debugging in StockController i am getting null pointer Exception in —-> if (optional.isPresent())

    • Andrej Buday says:

      Hi Ajith

      From first glance, I think your problem is with the Spring application context. You are running a Mock test with @RunWith(MockitoJunitRunner.class). However, maybe you want to @RunWith(SpringRunner.class) as the SpringRunner provides support for loading a Spring Application Context and having beans @Autowired into your test instance. MockitoJunitRunner will you create a Mock object based on the type you demand – StockService in your guess. Have you tried to go this way? Hope it helped.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.