Reputation: 1004
I am using Spring boot and Mockito for testing. I have been able to write test cases for Service layer and they re working fine. But, the test cases for DAO layer do not. The jdbcTemplate
object that is mocked and autowired gives null
pointer when executing the test case. Below are the details:
My DAOTest
class:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EcommerceApplication.class)
public classEcommerceDaoTest {
@InjectMocks
private IEcommerceDao ecommerceDao = new EcommerceDaoImpl();
@Mock
@Autowired
private JdbcTemplate as400JdbcTemplate;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
}
@Test
public void checkOrderExistsTest() throws EcommerceException{
Mockito.when(as400JdbcTemplate.queryForObject(queryForOrder,new Object[]
{"1000"}, int.class)).thenReturn(1);
boolean exists =
ecommerceDao.checkOrderExists("1000");
assertTrue(exists);
}
}
EcommerceDAOImpl.java:
@Override
public boolean checkOrderExists(String orderNo)throws EcommerceException{
boolean doesExist = false;
int count = 0;
try{
count= as400JdbcTemplate.queryForObject(queryForOrder, new Object[]{orderNo}, int.class);
if(count >0){
doesExist = true;
}
}
catch(Exception e){
}
return doesExist;
}
AS400Config.java:
@Bean
@Autowired
public JdbcTemplate as400JdbcTemplate(@Qualifier("as400DataSource")DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
ECommerceApplication.java
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class })
@EnableTransactionManagement
@Import(As400Configuration.class)
public class EcommerceApplication {
public static void main(String[] args) {
SpringApplication.run(EcommerceApplication.class, args);
}
}
When I am running the test case, I am getting NullPointerException
for as400JdbcTemplate
. The functionality works fine as is. Its just the test cases for DAO layer that fail because of the inability of the jdbcTemplate
to get mocked/autowired.
Please let me know where I am going wrong.
Upvotes: 2
Views: 10089
Reputation: 5407
You don't need to use @Mock
and @Autowired
at the same time. Use only @Mock
:
@Mock
private JdbcTemplate as400JdbcTemplate;
Use instead of @RunWith(SpringRunner.class)
--> @RunWith(MockitoJUnitRunner.class)
Also to inject mock into DAO you can use ReflectionTestUtils from spring test.
public static void setField(Class targetClass, String name, Object value)
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(ecommerceDao ,"as400JdbcTemplate" ,
as400JdbcTemplate);
}
@Mock
private JdbcTemplate as400JdbcTemplate;
Upvotes: 2