Enterprise Java

Testing with Mockito

1) Register MockitoExtension

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

2) Create the mock

@Mock
    private ObjectRepo mockRepo;

3) Inject the mock

@InjectMocks
    private ObjectService objectService;

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

4) Define the behavior

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

5) Test

var result = ObjectService.findById(ID);

6) Verify

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

7) Validate

assertAll(
                () -> assertNotNull(result),
                () -> assertEquals(objectDAO.getId(), result.getId())
        );
    }
}
Published on Java Code Geeks with permission by Eidher Julian, partner at our JCG program. See the original article here: Testing with Mockito

Opinions expressed by Java Code Geeks contributors are their own.

Eidher Julian

Eidher Julian is a Systems Engineer and Software Engineering Specialist with 13+ years of experience as a Java developer. He is an Oracle Certified Associate and SOA Certified Architect.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Billius
Billius
2 years ago

Thanks a lot for this algorithm, that is really useful for me

Back to top button