eidher
Posted on January 14, 2021
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())
);
}
}
💖 💪 🙅 🚩
eidher
Posted on January 14, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev Improving Code Quality and Accelerating Development: The Continuous Testing Way
February 9, 2024