java 如何使用 Mockito 和 jUnit 模拟持久化和实体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26945891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mock persisting and Entity with Mockito and jUnit
提问by Patrick
I'm trying to find a way to test my entity using Mockito;
我正在尝试找到一种使用 Mockito 测试我的实体的方法;
This is the simple test method:
这是简单的测试方法:
@Mock
private EntityManager em;
@Test
public void persistArticleWithValidArticleSetsArticleId() {
Article article = new Article();
em.persist(article);
assertThat(article.getId(), is(not(0L)));
}
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 将 Id 从 0L 更改为 1L 的行为?可能对可读性的阻碍最小。
Edit: Some extra information; Outside test-scope the EntityManager is produced by an application-container
编辑:一些额外的信息;在测试范围之外,EntityManager 由应用程序容器生成
回答by Dawood ibn Kareem
You could use a Mockito Answer
for this.
您可以Answer
为此使用 Mockito 。
doAnswer(new Answer<Object>(){
@Override
public Object answer(InvocationOnMock invocation){
Article article = (Article) invocation.getArguments()[0];
article.setId(1L);
return null;
}
}).when(em).persist(any(Article.class));
This tells Mockito that when the persist
method is called, the first argument should have its setId
method invoked.
这告诉 Mockito 当persist
方法被调用时,第一个参数应该setId
调用它的方法。
But if you do this, I don't understand what the purpose of the test would be. You'd really just be testing that the Mockito Answer
mechanism works, not that the code of Article
or of EntityManager
works correctly.
但是如果你这样做,我不明白测试的目的是什么。您实际上只是在测试 MockitoAnswer
机制是否有效,而不是Article
或的代码EntityManager
是否正常工作。
回答by JB Nizet
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;
}
}
And then
接着
doAnswer(new AssignIdToArticleAnswer(1L)).when(em).persist(any(Article.class));
回答by gmode
similar answer as above, but with lambdas
与上面类似的答案,但使用 lambdas
doAnswer((InvocationOnMock invocation) -> {
Article article = (Article) invocation.getArguments()[0];
article.setId(1L);
return null;
}).when(em).persist(any(Article.class));