JUnit test: null pointer exception

2019-08-20 04:03发布

问题:

I am using Spring with EXT JS and hibernate to populate a EXT JS form on a webpage using tomcat... I have the table populating using a method that accesses the database and returns my HQL statement

Now i am trying to execute a simple JUnit test to count the number of records returned but when i am calling the method in the JUint test that populates the EXT JS form, it returns this excception... I dont know why

JUnit Test class

package com.fexco.helloworld.web;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.fexco.helloworld.web.dao.CustomerDaoImpl;
import com.fexco.helloworld.web.model.Customer;

/**
* Unit test for simple App.
*   /
public class CustomerServiceTest {

@Autowired
private CustomerDaoImpl customerDaoImpl;

@Test
public void findAllCustomersTest() {        
    List<Customer> list = customerDaoImpl.findAllCustomers();
    int numberInDatabase = list.size();
    assertEquals(5, numberInDatabase);
}

}

my method accessing the database

public List<Customer> findAllCustomers(){
    List<Customer> list = getHibernateTemplate().find("from Customer");
    return list;
}

and my method calling the method accessing the database

public List<Customer> returnAllCustomers(){
    List<Customer> list = customerDaoImpl.findAllCustomers();
    return list;
}

you can see here that the form is populated with items from the database using the same method as in junit(findAllCustomers())

Does anybody have any ideas?

回答1:

Add following line before class CustomerServiceTest

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = { "file:src/main/resources/app-context.xml" })
 public class CustomerServiceTest {....

Where src/main/resources/app-context.xml - is path to your application context. Its good, to create separate context for tests.

EDIT

You also need to have spring-test.jar in the classpath. Dependency for maven:

       <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-version}</version>
        </dependency>


回答2:

You did not load your Spring context in your unit test.

you can take a look at the Spring documentation here : http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/testing.html

And an example : Spring: JUnit-Test: applicationContext is not loaded