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 模拟持久化和实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Mockito 和 jUnit 模拟持久化和实体


基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01