DEV Community

eidher
eidher

Posted on

 

Testing with Mockito

1) Register MockitoExtension

@ExtendWith(MockitoExtension.class)
class ObjectTest {
    static final Long ID = 1L;
Enter fullscreen mode Exit fullscreen mode

2) Create the mock

    @Mock
    private ObjectRepo mockRepo;
Enter fullscreen mode Exit fullscreen mode

3) Inject the mock

    @InjectMocks
    private ObjectService objectService;

    @Test
    void whenfindByIdThenReturnResult() {
        var objectDAO = new ObjectDAO();
        objectDAO.setId(ID);
Enter fullscreen mode Exit fullscreen mode

4) Define the behavior

        when(mockRepo.findById(any(Long.class))).thenReturn(Optional.of(objectDAO));
Enter fullscreen mode Exit fullscreen mode

5) Test

        var result = ObjectService.findById(ID);
Enter fullscreen mode Exit fullscreen mode

6) Verify

        verify(mockRepo, times(1)).findById(any(Long.class));
Enter fullscreen mode Exit fullscreen mode

7) Validate

        assertAll(
                () -> assertNotNull(result),
                () -> assertEquals(objectDAO.getId(), result.getId())
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesnโ€™t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.