Header Ads Widget

Ticker

6/recent/ticker-posts

Testing con Mockito

 1) Registrar MockitoExtension

1
2
3
@ExtendWith(MockitoExtension.class)
class ObjectTest {
    static final Long ID = 1L;

2) Crea el simulacro

1
2
@Mock
    private ObjectRepo mockRepo;

3) Inyecta el simulacro

1
2
3
4
5
6
7
@InjectMocks
    private ObjectService objectService;
 
    @Test
    void whenfindByIdThenReturnResult() {
        var objectDAO = new ObjectDAO();
        objectDAO.setId(ID);

4) Definir el comportamiento

1
when(mockRepo.findById(any(Long.class))).thenReturn(Optional.of(objectDAO));

5) Prueba

1
var result = ObjectService.findById(ID);

6) Verificar

1
verify(mockRepo, times(1)).findById(any(Long.class));

7) Validar

1
2
3
4
5
6
assertAll(
                () -> assertNotNull(result),
                () -> assertEquals(objectDAO.getId(), result.getId())
        );
    }
}

Publicar un comentario

0 Comentarios