Hi
I am new to
Mockito and trying to write a
test for my demo project. I have a project, using Spring 5 and Hibernate. I have a DAO class which use Hibernate session and query.
@Repository
@Transactional
public class CustomerDaoImpl implements CustomerDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public Customer getCustomerById(int id) {
Session session = null;
Customer customer = null;
try{
session = sessionFactory.openSession();
customer = session.find(Customer.class, id);
}catch(Exception e) {
throw (e);
}finally {
session.close();
}
return customer;
}
}
// Test Class
@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
@ContextConfiguration(locations = "classpath:spring-hibernate-config-test.xml")
public class CustomerDaoTest {
@InjectMocks
private CustomerDaoImpl customerDao;
@Mock
SessionFactory sessionFactory;
Customer customer;
@Before
public void setupMock(){
MockitoAnnotations.initMocks(this);
sessionFactory = mock(SessionFactory.class);
customerDao.setSessionFactory(sessionFactory);
}
@Test
@Transactional
@Rollback(true)
@DisplayName("DAO: Find customer by given id")
public void testGetCustomerById() {
int customerId = 14;
Customer customer = new Customer(14, "Mike");
when(sessionFactory.openSession().find(Customer.class, customerId)).thenReturn(customer);
assertNotNull(customer);
assertEquals(customerId, customer.getIfCustomerId());
}
}
Error:
java.lang.NullPointerException
at com.primis.dao.CustomerDaoTest.testGetCustomerById(CustomerDaoTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
For some reason my session is null. Please can someone advice where I am going wrong.
Thank you