Search code examples
javajunitmockitohamcrest

How to mock persisting and Entity with Mockito and jUnit


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


Solution

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