我和学生做了一个小小的申请......
我有一个带有studentId(整数),firstName(字符串)和lastName(字符串)的Student.java类,带有geters和setter以及构造函数
public Student(Integer studentId, String firstName, String lastName) {
this();
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
}
在App.java中(Maven为我生成了这个类),我得到了这段代码:
@PersistenceContext
static
EntityManager em;
public static Boolean addStudent(Student s) {
try{
em.persist(s);
em.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
return true;
}
然后我创建了一个名为testStudent
的数据库在我的pom.xml文件中,我添加了这一行:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<server>localhost</server>
<database>testStudent</database>
<port>8080</port>
</properties>
我希望你将这个数据库添加到maven项目中......?
然后我在另一个包中进行了jUnit测试:
AppT.java,我得到了这个测试:
@Test
public void testAddStudent(){
Student s = new Student(4,"aaa","bbb");
Boolean b = App.addStudent(s);
assert(b);
}
一旦我运行测试,App.java就行了一个java.lang.NullPointerException,我坚持让新学生......
em.persist(s); // here is the exception
em.flush();
现在我不明白,这是怎么可能的,在我的测试中,我创造了一个新的学生,他有自己的属性......他不应该是空的
有人可以向我解释一下吗?谢谢 顺便说一句。我也在使用Arquillian ....如果这有帮助...
答案 0 :(得分:-1)
我想在你的场景中,Student不是null,但是EntityManager em的实例可能为null。请检查它是如何初始化测试环境的