Skip to content
Advertisement

Mock Property value resides in constructor and add that mock while using @injectBean annotation

I have a class where one attribute is getting value from outer repo.

public class Demo() {
   private final Repository repository;
   private final long attr;

   public Demo(Repository repository) {
     this.repository = repository;
     this.attr = this.getValue();
   }
  
   private Long getValue() {
     return repository.getValue();
   }
   ... Rest of the code
}

Now I want to write an unit test for it.

import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class DemoTest() {
  @Mock
  private Repository repository;

  @InjectMocks
  private Demo demo;

  @BeforeEach
  void setUp() {
    registrationUtil = new RegistrationUtil();
    MockitoAnnotations.initMocks(this);

}

When I run this snippet, it shows a null pointer exception in repository.getValue() May I know how can I mock the value properly to avoid exception?

Advertisement

Answer

The reason that InjectMocks is not working could be because your Repository field is Final.

Kindly see Reference: Mockito injection not working for constructor AND setter mocks together

Resolution:

Example Demo Class:

Notice it is not a Spring Class, Just a simple pojo) just to showcase that we are not autowiring anything here.

import com.example.mongodb.embedded.demo.repository.UserRepository;

public class Demo {

    private final UserRepository repository;

    public Demo(UserRepository repository) {
        this.repository = repository;
    }

    private Long getValue() {
        return repository.count();
    }

    public String toString(){
        return "Count: " + getValue();
    }
}

package com.example.demo;

import com.example.mongodb.embedded.demo.repository.UserRepository;
import com.example.mongodb.embedded.demo.service.Demo;

import org.junit.Rule;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
class DemoApplicationTest {

    @Mock
    private UserRepository userRepository;

    private Demo noneAutoWiredDemoInstance;

    @Test
    public void testConstructorCreation() {

        MockitoAnnotations.initMocks(this);
        Mockito.when(userRepository.count()).thenReturn(0L);

        noneAutoWiredDemoInstance = new Demo(userRepository);

        Assertions.assertEquals("Count: 0", noneAutoWiredDemoInstance.toString());
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement