【问题标题】:Null Pointer Exception while mocking get Entity Manager模拟获取实体管理器时出现空指针异常
【发布时间】: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


【解决方案1】:

严格来说,就单元测试而言...您要测试什么? 如果您正在测试 ProductJPAController,它只会调用 EntityManager,并且它已经过测试。

尽管如此,由于 JPAController 使用静态类来生成 entityManager 实例,用 mockito 模拟它并不容易......(Powermock 会允许这样做,但它真的需要使用它吗?)

我看到的唯一解决方案是监视 productJpaControllerInstance,您将不得不模拟以下调用:

  • getEntityManager
  • getTransaction(记得模拟对开始和提交方法的调用)
  • 坚持
  • 关闭

返回模拟元素以执行测试。

希望对你有帮助...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多