vendredi 20 janvier 2017

Check function call argument explicitly with `verify` or implicitly with `when`?

What is the best way to check that right argument comes to right place with Mockito?

Consider next unit-test:

@Test
public void getProjectByIdTest() {
    Long projectId = 1L;
    ProjectEntity expectedProject = mock(ProjectEntity.class);
    when(projectRepository.findOne(anyLong())).thenReturn(expectedProject);

    assertThat(projectService.getById(projectId), is(expectedProject));
    verify(projectRepository).findOne(projectId);
}

Here we check that projectService passes it's argument to the right place with verify, explicitly.

Now check this unit-test:

@Test
public void getProjectByIdTest() {
    Long projectId = 1L;
    ProjectEntity expectedProject = mock(ProjectEntity.class);
    when(projectRepository.findOne(projectId)).thenReturn(expectedProject);

    assertThat(projectService.getById(projectId), is(expectedProject));
}

It also checks that projectService passed its argument to right place, but implicitly, with when (so if projectService will actually pass some random number, assertThat will fail).

So how this should be done? It seems to me that without that verify this test looses some clarity; but from the other hand its shorter.

Aucun commentaire:

Enregistrer un commentaire