给定样本两个类,我在尝试模拟jpacontroller中的getentityManager()时,我会得到一个无效的指针,其中有人在Mockito上有知识。
。产品JPA控制器
public class ProductjpaController extends JpaController {
public ProductjpaController() {
super(Product.class);
}
public Product create(Product product) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(product);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
return product;
}
}
JPA控制器
public EntityManager getEntityManager() {
EntityManagerFactory emf = null;
Map<String, String> properties = new HashMap<>();
final String url = "jdbc:mysql://" + getHost(dBModule) + ":" + getPort(dBModule) + "/" + database+"?useSSL=false";
properties.put("hibernate.connection.url", url);
properties.put("hibernate.connection.username", getUser(dBModule));
properties.put("hibernate.connection.password", getPassword(dBModule));
properties.put("hibernate.ejb.entitymanager_factory_name", database);
try {
emf = Persistence.createEntityManagerFactory("templatePU", properties);
} catch (Exception e) {
e.printStackTrace(); // strangely, this works, but the next two lines don't
LOG.log(Level.SEVERE, "unexpected exception", Utilities.getStackTrace(e));
LOG.log(Level.SEVERE, "cause of unexpected exception", Utilities.getStackTrace(e.getCause()));
}
return emf.createEntityManager();
}
严格来说,就单位测试而言……您想测试什么?如果您正在测试productjpacontroller,则只会对EntityManager进行呼叫,并且已经进行了测试。
尽管如此,由于jpacontroller使用静态类来生成EntityManager实例,因此使用Mockito嘲笑它并不容易...(PowerMock将允许使用它,但是真的需要使用它吗?)
)我看到的唯一解决方案是监视Product jpacontrollerinstance,您必须嘲笑:
- getentityManager
- getTransaction(记住要模拟开始和提交方法的呼叫)
- 坚持
- 关闭
返回模拟元素执行测试。
希望它有帮助...