Search code examples
javajunitmockitojunit4powermock

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();

Solution

  • 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);
        }
    }