How to mock persisting and Entity with Mockito and jUnit

前端 未结 3 2027
终归单人心
终归单人心 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:16

    You could use a Mockito Answer for this.

    doAnswer(new Answer(){
         @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.

    提交回复
    热议问题