【发布时间】:2018-06-02 19:45:44
【问题描述】:
给定示例两个类,我在尝试模拟 JpaController 中的 getEntityManager() 时遇到空指针异常,请了解模拟的人提供建议。
产品 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();
}
【问题讨论】:
-
我们可以使用堆栈跟踪,并尝试模拟。我在这里看不到任何
Mock。 -
你的问题真的不是很清楚。这里没有实际的模拟代码。你在嘲讽什么?你怎么嘲讽它?哪一行抛出异常?
-
@DawoodibnKareem 我试图从代码中删减很多部分,以免使其模棱两可,但是在上面的场景中如何模拟 getEntityManager
标签: java mockito powermockito java-ee-5 junit5