模拟获取实体管理器时出现空指针异常

问题描述 投票:0回答:1

给定样本两个类,我在尝试模拟Jpa控制器中的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();
}
java mockito powermockito java-ee-5 junit5
1个回答
0
投票

严格来说,在单元测试方面...你想测试什么?如果您正在测试ProductJPAController,它只会调用EntityManager,并且它已经过测试。

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

我看到的唯一解决方案是监视productJpaControllerInstance,你必须模拟调用:

  • getEntityManager
  • getTransaction(记得模拟调用begin和commit方法)
  • 坚持

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

希望能帮助到你...

© www.soinside.com 2019 - 2024. All rights reserved.