Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failing to mock @Autowired Object

I am using Junit4 and Mockito for test cases, in the following code I am trying to mock a autowired object which throws null pointer exception inside the mocking class which means autowired object is not mocking properly

ContentDao.java

public class ContentDao {

  @Autowired 
  private ConfigProperties configProperties;

  public void fuction() {
  int batchSize = configProperties.getBatchSize();
}

ConfigProperties.java

@ConfigurationProperties(ignoreUnknownFields = false, prefix = "cleanup")
public class ConfigProperties {

  private int batchSize;

  public int getBatchSize() {
    return batchSize;
  }
}

Trying to mock ConfigProperties.

@RunWith(MockitoJUnitRunner.class)
public class ContentDaoTest{

   @InjectMocks
   private ContentDao contentDao;

   @Mock
   private ConfigProperties configProperties;

   @Test
   public void functionTest(){
      configProperties = mock(ConfigProperties.class);
      when(configProperties.getBatchSize()).thenReturn(100);
      ContentDao contentDao = new ContentDao();
      contentDao.funtion();
   }

funtion is called, but I get NPE in below line. Please help I am stuck here.

int batchSize = configProperties.getBatchSize();
like image 392
Kiran Kumar Avatar asked Jan 29 '23 23:01

Kiran Kumar


1 Answers

If you set @Mock for configProperties, you should not mock again configProperties = mock(ConfigProperties.class); In the same idea, as you set @InjectMocks for contentDao, you should not instantiate a new contentDao.

@RunWith(MockitoJUnitRunner.class)
public class ContentDaoTest {

    @InjectMocks
    private ContentDao contentDao;

    @Mock
    private ConfigProperties configProperties;

    @Test
    public void functionTest() {
        Mockito.when(configProperties.getBatchSize()).thenReturn(100);
        Assertions.assertThat(contentDao.getBatchSize()).isEqualTo(100);
    }
}
like image 52
OlivierTerrien Avatar answered Feb 02 '23 10:02

OlivierTerrien