如何使用Mockito和jUnit模拟持久化和实体 [英] How to mock persisting and Entity with Mockito and jUnit
本文介绍了如何使用Mockito和jUnit模拟持久化和实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试找到一种使用Mockito测试实体的方法;
I'm trying to find a way to test my entity using Mockito;
这是简单的测试方法:
@Mock
private EntityManager em;
@Test
public void persistArticleWithValidArticleSetsArticleId() {
Article article = new Article();
em.persist(article);
assertThat(article.getId(), is(not(0L)));
}
我如何最好地模拟EntityManager将ID从0L更改为1L的行为?可能会减少可读性的障碍.
How do I best mock the behaviour that the EntityManager changes the Id from 0L to i.e. 1L? Possibly with the least obstructions in readability.
一些额外的信息;在外部测试范围内,EntityManager是由应用程序容器
Some extra information; Outside test-scope the EntityManager is produced by an application-container
推荐答案
public class AssignIdToArticleAnswer implements Answer<Void> {
private final Long id;
public AssignIdToArticleAnswer(Long id) {
this.id = id;
}
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Article article = (Article) invocation.getArguments()[0];
article.setId(id);
return null;
}
}
然后
doAnswer(new AssignIdToArticleAnswer(1L)).when(em).persist(any(Article.class));
这篇关于如何使用Mockito和jUnit模拟持久化和实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文