给出了两个类的示例,我在尝试模拟JpaController中的getEntityManager()时得到一个空指针exeption,有人知道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();
}
答案 0 :(得分:0)
严格来说,在单元测试方面...你想测试什么? 如果您正在测试ProductJPAController,它只会调用EntityManager,并且已经过测试。
然而,由于JPAController使用静态类来生成entityManager实例,使用mockito模拟它并不容易......(Powermock会允许这样做,但是真的需要使用它吗?)
我看到的唯一解决方案是监视productJpaControllerInstance,你必须模拟调用:
返回模拟元素以执行测试。
希望它有所帮助...