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:

public final class DocumentRepositoryTest {

    private DocumentRepository documentRepository;

    public void testConvertToNewDocument() {
        String paperColor = new String("white");
        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
    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{
    private StockService stockService;

    public GatewayResponse findProduct(String productId) {
    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

    public void ControllerTest()
    StockController stockController;
    StockService stockService;
    public void findProductTest()
    String productId = “pr455”;
    Product pr = new 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.