JUnit5 (Unit testing):
Tests short and isolated piece of code e.g. getMethod() etc. Normally junit code is
not expected to communicate with remote systems e.g. DB, MS etc.
Quick to run.
RESTAssured (Integration Tests):
It tests the response for a RESTful web service.
With RESTAssured framework we are testing the result of entire webservice endpoint.
===============================================================
Add Dependency: spring-boot-starter-test
Maven will download JUnit, Hamcrest & Mockito framework for Object mocking.
===============================================================
Mocking
@InjectMocks
UserServiceImpl userService
@Mock
UserRepository userRepository
@BeforeEach
void setUp throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
final void testGetUser(){
UserEntity userEntity = new UserEntity();
userEntity.setId(1L); //add other attributes
when(userRepository.findByEmail( anyString())).thenReturn(userEntity);
Mockito.doNothing().when(amazonSES).verifyEmail(any(UserDto.class));
UserDto userDto = userService.getFirstName("someName"));
assertNotNull(userDto);
assertEquals("behl", userDto.getFirstName());
assertEquals(userDto.getPassword.size()==30);
}
@Test
final void testGetUser_UsernameNotFoundException(){
when(userRepository.findByEmail(anyString())).thenReturn(null);
assertThrows(UsernameNotFoundException.class,
() -> {
userService.getUser("test@test.com");
});
}
===============================================================
Integration Tests
@ExtendWith(SpringExtension.class) //this will load Spring context
i.e. the app will start.
@SpringBootTest
class UtilsTest{
@Autowired
Utils utils;
@BeforeEach
void setUp() throws Exception {
String userId = utils.generateUserId(30);
assertNotNull(userId);
assertTrue(userId.length() == 30);
}
@Test //Unit Test
final void testGenerateUserId(){
String userId = utils.generateUserId(30);
assertNotNull(userId);
assertTrue(userId.length() == 30);
}
@Test
final void testHasTokenExpired(){
String token = "JWT.token.value";
boolean hasTokenExpired = Utils.hasTokenExpired(token); //e.g. this
will check with DB
assertFalse(hasTokenExpired);
}
}
===============================================================
===============================================================
===============================================================
===============================================================