2

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);
    }
}
Nidheesh
  • 4,390
  • 29
  • 87
  • 150
  • employeeList.getEmpList() is getting null. But I have tried with a simple method employeeList.check(), without any hibernate database queries and have worked without error.When trying with database causes the error. – Nidheesh Dec 22 '11 at 05:20
  • I have posted the class. – Nidheesh Dec 22 '11 at 05:38
  • Do we need to set up the connection in test class also? Or the same way how we test the other methods! – Nidheesh Dec 22 '11 at 06:18
  • What error are you getting now. Where is the /spring/servlet-config.xml file - if it is under WEB-INF the testcase won't be able to access it. – gkamal Dec 22 '11 at 10:22
  • Yes it is under WEB-INF. – Nidheesh Dec 22 '11 at 10:31

2 Answers2

3

The null pointer exception is because hibernateTemplate is null (check line EmployeeList.java:209). This is happening because you are creating a new EmployeeList object in the test class - it should be retrieved from the spring context.

You need to configure your test to create a spring application context and then inject the EmployeeList as a dependency

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("<put your spring config file here>")
public class EmployeeListTest extends TestCase {
    @Autowired
    private EmployeeList employeeList
gkamal
  • 20,777
  • 4
  • 60
  • 57
  • @gkamal-But error on : `Class cannot be resolved to a type` and `Class cannot be resolved to a type`. I'm using junit-4.9.jar. – Nidheesh Dec 22 '11 at 07:34
  • @gkamal- As you said,I tried to retrieve the hibernateTemplate. I put the code in edited portion above. Where I went wrong? – Nidheesh Dec 22 '11 at 09:38
0

Did you try to debug the term :

List <Employee> result =  hibernateTemplate.find("from Employee"); 

Are there any objects there? what if there are no Employees in the List is the list created? Maby its NULL then! Basically you are not supposed to make Database access operations in your Unitests, these cost you too much time, the alternative is to create mock ups which simulate your data objects in a unitest environment.

Read: How to simulate a DB for testing (Java)?

What about the Line:

List<Employee> employees = employeeList.getEmpList();

I think the methode public List<Employee> empList() must have get and set Methiods so you can call:

employeeList.getEmpList();

Are they there?

Community
  • 1
  • 1
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
  • Yes , I have called the method like, `employeeList.getEmpList();` itself in the test class.I'm sure my `empList()` is not null. – Nidheesh Dec 22 '11 at 05:29
  • And are there any Objects in the DB-Table? – CloudyMarble Dec 22 '11 at 05:30
  • Yes it is there.. I doubt , anything more I need to add while doing test on DB queries? – Nidheesh Dec 22 '11 at 05:32
  • Do we need to set up the connection in test class also? Or the same way how we test the other methods! – Nidheesh Dec 22 '11 at 06:13
  • Try to access the Find methode only if (hibernateTemplate != NULL) – CloudyMarble Dec 22 '11 at 06:18
  • It seems your Template is NULL, i noticed the line where you create the Template isnt called, dont you have to call the employeeList.setSessionFactory methode where you create the Template?? – CloudyMarble Dec 22 '11 at 06:20
  • Yea, hibernateTemplate is getting null in the test class. But when I added a test case `@Test public void testSetSessionFactory(SessionFactory sessionFactory)throws HibernateException, SQLException { this.hibernateTemplate = new HibernateTemplate(sessionFactory); assertNotNull(hibernateTemplate); }` , the test case is not executing! – Nidheesh Dec 22 '11 at 06:54
  • Test-methods cannot have any parameters, JUnit does not know what to use as the parameter. You either need to use a mocked HibernateTemplate and set that to your DAO-class either via setter or with ReflectionTestUtils before the test or turn the test into an integration test like in @gkamal's answer. – esaj Dec 22 '11 at 07:05
  • What do you mean its not executing? In your test EmployeeListTest You just need to retrieve the Template from your EmpoloyeeList class where you create it, then it should work, you can implement a CreateTemplate methode and test it so you make sure this part works. – CloudyMarble Dec 22 '11 at 07:06
  • @esaj: What parameter do you mean, the hibernateTemplate is static in the EmployeeList class, he can access it from test. – CloudyMarble Dec 22 '11 at 07:09
  • @O.D I was referring to ni.ep's comment above mine, the '@Test public void testSetSessionFactory(SessionFactory sessionFactory)' won't get executed, because JUnit does not know what to use as the 'sessionFactory'-parameter. – esaj Dec 22 '11 at 07:11
  • Right, it shouldbe also as static member in this case, or as mentioned mocked up which is the better solution but guess its another issue. – CloudyMarble Dec 22 '11 at 07:16
  • @ esaj: Can you provide any link for how to use ReflectionTestUtils.I'm new to JUnit – Nidheesh Dec 22 '11 at 08:59
  • @O.D: I have done a try to retrieve the hibernateTemplate, got errors.(edited code is there above all comments.) – Nidheesh Dec 22 '11 at 09:05