I'm new to JUnit testing.Whenever I tried to test a method which have a hibernate query results null pointer error, like
java.lang.NullPointerException
at com.fetchinglife.application.modules.employee.view.EmployeeList.empList(EmployeeList.java:209)
My test class is :
public class EmployeeListTest extends TestCase {
private EmployeeList employeeList = new EmployeeList();
public static HibernateTemplate hibernateTemplate;
@BeforeClass
public void setUpBeforeClass() throws Exception {
SessionFactory sessionFactory = this.hibernateTemplate.getSessionFactory();
Session session = sessionFactory.openSession();
System.out.println("in before");
}
@Test
public void testGetEmployees() throws HibernateException, SQLException {
List<Employee> employees = employeeList.getEmpList();
assertNotNull(employees);
}
But Null pointer error for testGetEmployees()
And my method in EmployeeList
is :
public List<Employee> empList() {
try
{
@SuppressWarnings("unchecked")
List <Employee> result = hibernateTemplate.find("from Employee");
return result;
}
finally {
}
}
What I have to add more?I'm using JUnit 4.
My EmployeeList.java here.
@Component("employeeList")
@SessionScoped
@Repository
public class EmployeeList implements Serializable {
private static final long serialVersionUID = -2417394435764260084L;
public static HibernateTemplate hibernateTemplate;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory)
{
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
private Employee employee = new Employee();
public List<Employee> getEmployees() throws HibernateException, SQLException {
List<Employee> employees = new ArrayList<Employee>();
System.out.println("in getEmployeess");
employees.addAll(empList());
return employees;
}
public List<Employee> empList() {
System.out.println(" find all employees: ");
try
{
@SuppressWarnings("unchecked")
List <Employee> result = hibernateTemplate.find("from Employee");
return result;
}
finally {
}
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
I have tried to retrieve hibernateTemplate but still error. I don't know where I got wrong.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/spring/servlet-config.xml")
public class EmployeeListTest extends TestCase {
private static HibernateTemplate hibernateTemplate;
@Autowired
private EmployeeList employeeList;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
Session session = sessionFactory.openSession();
}
@Test
public void testGetEmployees() throws HibernateException, SQLException {
List<Employee> employees = employeeList.getEmployees();
assertNotNull(employees);
}
}