gpt4 book ai didi

java - 如何为EntityManager事务编写单元测试?

转载 作者:行者123 更新时间:2023-12-02 09:41:20 24 4
gpt4 key购买 nike

我正在尝试为现有函数编写单元测试,该函数使用 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(),我的测试仍然会通过。有没有好的测试方法?

最佳答案

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

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

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

关于java - 如何为EntityManager事务编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57046281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com