JUnit测试NullPointerException

时间:2015-08-06 12:26:35

标签: java spring hibernate junit nullpointerexception

我用Spring,Hibernate编写WEB应用程序,我有CRUD功能,我需要创建测试,工作者的所有功能,但测试不起作用。

这是我对JUnit的第一次测试,我无法成功运行测试,我有NullPointerException。我有类控制器Handler.java,模型类Student.java

这是我的代码。

Student.java

public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private int id;

    @Column(name="lastName")
    private String lastName;

    @Column(name="firstName")
    private String firstName;

    @Column(name="middleName")
    private String middleName;

    @Column(name="groups")
    private String group;

    @Column(name="rating")
    private double average;

    //setter and getter, constructor

Handler.java - 这是控制器

@Controller
public class Handler {

    @Autowired
    private StudentDataAccessObject studentDAO;

    public void setStudentDAO(StudentDataAccessObject studentDAO) {
        this.studentDAO = studentDAO;
    }
    /**
     * @param student data from the client
     * @return return new data
     * */
    @RequestMapping(value="add", method=RequestMethod.POST)
    @ResponseBody
    public Student addStudent(@RequestBody Student student){
        studentDAO.addStudentToDatabase(student);
        return student;
    }
    ...
}

StudentDataAccessObject.java

public class StudentDataAccessObject implements DatabaseStudent{        
    @Autowired
    private SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }
    /**
     * This method add student to database, use framework Hibernate
     * @param student add to database
     * */
    public void addStudentToDatabase(Student student) {
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        session.save(student);
        transaction.commit();
    }
    ...
}

TestHandler.java 这是测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"Student-servlet.xml"})
public class TestDAO {
    @Test
    public void testHandler(){
        Handler handler = new Handler();
        Student student = new Student("Test1","Test2","Test3","Test4",4);
        handler.addStudent(student);
    }
    ...
}

Student-servlet.xml

<context:component-scan base-package="home.spring.mvc.controller"/>
<mvc:annotation-driven/>
<mvc:resources mapping="/views/**" location="/views/"/>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/student" />
    <property name="username" value="********" />
    <property name="password" value="********" /> 
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>home.data.model.student.Student</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.transaction.auto_close_session">true</prop>
        </props>
    </property>
</bean>

<bean id="studentDAO" class="home.data.db.dao.StudentDataAccessObject">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

1 个答案:

答案 0 :(得分:2)

您正在手动创建处理程序。 Spring应该创建它。否则依赖注入不起作用。如果没有依赖注入,你的dao将为null。你有两个选择,让spring自己创建你的处理程序或自己创建处理程序,但手动设置你的dao。

以下是修复Null Pointer Exception

的示例手动创建
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"Student-servlet.xml"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
public class TestDAO {

   @Autowired
   private DatabaseStudent studentDAO;

    @Test
    public void testHandler(){
        Assert.assertNotNull(studentDAO);
        Handler handler = new Handler();
        handler.setStudentDAO(studentDAO);
        Student student = new Student("Test1","Test2","Test3","Test4",4);
        handler.addStudent(student);
    }
    ...
}