Java 如何使用jUnit测试解决Maven项目中的一个错误NullPointerException?
我和一个学生做了一个小申请Java 如何使用jUnit测试解决Maven项目中的一个错误NullPointerException?,java,maven,junit,Java,Maven,Junit,我和一个学生做了一个小申请 em.persist(s); // here is the exception em.flush(); 我得到了一个Student.java类,其中包含studentId(整数)、firstName(字符串)和lastName(字符串)、geters和setter以及构造函数 public Student(Integer studentId, String firstName, String lastName) { this(); this.stud
em.persist(s); // here is the exception
em.flush();
我得到了一个Student.java类,其中包含studentId(整数)、firstName(字符串)和lastName(字符串)、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>
一旦我运行了测试,App.java中的行上就有一个java.lang.NullPointerException,在这里我将新学生保留下来
em.persist(s); // here is the exception
em.flush();
现在我不明白,这怎么可能,在我的测试中,我创建了一个新的学生,有他自己的属性…他不应该是空的
有人能给我解释一下吗?谢谢
顺便说一句,我也在使用Arquillian…如果这有帮助的话…我猜在您的场景中,Student不是null,但是EntityManager em的实例可能是null。请检查它是如何为测试环境初始化的我只有@PersistenceContext static EntityManager em;在我的App.java类中……没有什么比回答更能说明问题了。它只是指出了可能存在的问题,但仍然没有解决问题。这就是自动关联依赖关系。但我猜它的一些模拟实例必须在某个地方初始化。请确保其已由您正在使用的测试框架初始化。可能是@Before或类似的位置我应该在测试所在的AppT.java中添加它,还是在实际函数所在的App.java中添加它?对于测试场景,它应该在AppT.java本身中,但不确定您的模拟框架如何为自动连线注释注入它