【问题标题】:How to write unit tests for EntityManager transaction?如何为 EntityManager 事务编写单元测试?
【发布时间】:2019-07-15 19:46:53
【问题描述】:

我正在尝试为使用 EntityManager 更新数据库字段值的现有函数编写单元测试。我的单元测试应该验证该类是否正确更新了值。当前代码如下所示:

public class MyClass {
    MyClass(EntityManager em) {
      this.em = em;
    }

    void updateValue() {
      em.getTransaction().begin();
      TypedQuery query = em.createQuery("select a from ...", MyResult.class);
      List<MyResult> results = query.getResultList(); 

      MyResult result = results.get(0);
      result.setInterestingValue(1);
      em.getTransaction().commit();
    }
}

我目前的单元测试方法:

@Mock EntityManager em;
@Mock TypedQuery query;

publid void test() {
   MyClass myClass = new MyClass(em);
   MyResult result = new MyResult();
   ArrayList<MyResult> resultList = new ArrayList<>();
   resultList.add(result);

   when(em.getTransaction()).thenReturn(mock(EntityTransaction.class));
   when(em.createQuery(anyString(), any())).thenReturn(query);
   when(query.getResultList()).thenReturn(resultList);

   myClass.updateValue();

   assertEquals(1, result.getInterestingValue());
}

我上面的单元测试验证了 MyResult 实例是否已更新。但是,它不会验证该值是否实际上是通过 EntityManager 更新的。换句话说,我想测试 EntityManager 是否在现有代码中正确使用。例如,即使我在 setInterestinvValue(1) 之前调用 commit(),我的测试仍然会通过。有什么好办法测试吗?

【问题讨论】:

标签: java unit-testing jpa mockito entitymanager


【解决方案1】:

如上所述,如果您使用 mockito,解决方案将是 - 使用 inOrder()

MyResult result = mock(MyResult.class);
EntityTransaction transaction = mock(EntityTransaction.class)

inOrder.verify(result).setInterestingValue(1);
inOrder.verify(transaction).commit();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 2018-10-17
    • 1970-01-01
    • 2018-01-17
    • 2012-01-06
    • 2019-03-17
    • 2016-04-02
    相关资源
    最近更新 更多