本文介紹了如何使用 Mockito 和 jUnit 模擬持久化和實(shí)體的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我正在嘗試尋找一種方法來(lái)使用 Mockito 測(cè)試我的實(shí)體;
I'm trying to find a way to test my entity using Mockito;
這是簡(jiǎn)單的測(cè)試方法:
@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.
一些額外的信息;在測(cè)試范圍之外,EntityManager 由應(yīng)用程序容器生成
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));
這篇關(guān)于如何使用 Mockito 和 jUnit 模擬持久化和實(shí)體的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!