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();
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With