How to mock persisting and Entity with Mockito and jUnit

半城伤御伤魂 提交于 2021-02-18 01:22:01

问题


I'm trying to find a way to test my entity using 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.

Edit: Some extra information; Outside test-scope the EntityManager is produced by an application-container


回答1:


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));



回答2:


You could use a Mockito Answer for this.

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.

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.




回答3:


similar answer as above, but with lambdas

   doAnswer((InvocationOnMock invocation) -> {
        Article article = (Article) invocation.getArguments()[0];
        article.setId(1L);
        return null;
    }).when(em).persist(any(Article.class));


来源:https://stackoverflow.com/questions/26945891/how-to-mock-persisting-and-entity-with-mockito-and-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!