How to mock persisting and Entity with Mockito and jUnit

前端 未结 3 2029
终归单人心
终归单人心 2021-02-09 19:42

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 persistArti         


        
3条回答
  •  情书的邮戳
    2021-02-09 20:11

    public class AssignIdToArticleAnswer implements Answer {
    
        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));
    

提交回复
热议问题