I was wondering if I wrote this test in a proper way to mock a real situation. Can you please provide any feedback?
I'm using Mockito in a Spring Boot environment. I'm new to Mockito and other mocking techniques, but I want to know if I'm on the right path or not.
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
class FileServiceImplTest {
@Mock
private UserPrincipal userPrincipal;
@Mock
private User user;
@Mock
private FileService fileService;
@BeforeEach
void initialize() {
user = new User("testUser", "[email protected]", "testPassword");
user.setId(1L);
user.setRoles(List.of(Role.User));
userPrincipal = UserPrincipal.create(user);
}
@Test
void usedMockUpsShouldNotBeNull() {
assertAll("All mock instaces of classes should not be null",
() -> assertNotNull(fileService),
() -> assertNotNull(userPrincipal),
() -> assertNotNull(user)
);
}
@Test
void collectionOfFilesShouldChangeAfterNewFileIsAdded_Mockito() throws ExecutionException, InterruptedException {
Image image = createImageFile();
List<? super File> files = createFilesCollection();
doReturn(files).when(fileService).getAll(userPrincipal);
int initialSize = fileService.getAll(userPrincipal).size();
fileService.save(image);
doReturn(files.add(image)).when(fileService).save(image);
int newSize = fileService.getAll(userPrincipal).size();
assertNotEquals(newSize, initialSize);
Mockito.verify(fileService, atLeast(2)).getAll(userPrincipal);
Mockito.verify(fileService).save(image);
}
}
@SpringBootTestis supposed to be used to do Integration Tests. When you do Integration Tests you usually don't want to mock stuff. Consider implementing Unit Tests instead and taking a look at stackoverflow.com/questions/5357601/… / dzone.com/articles/unit-and-integration-tests-in-spring-boot-2 / baeldung.com/spring-boot-testing.