Updated Junit5 article
package com.baeldung.junit5.mockito;
-import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
@@ -8,7 +9,6 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -26,21 +26,28 @@ import com.baeldung.junit5.mockito.service.Errors;
import com.baeldung.junit5.mockito.service.UserService;
@ExtendWith(MockitoExtension.class)
-public class UserServiceUnitTest {
+class UserServiceUnitTest {
UserService userService;
+
SettingRepository settingRepository;
- @Mock UserRepository userRepository;
- @Mock MailClient mailClient;
+
+ @Mock
+ UserRepository userRepository;
+
+ @Mock
+ MailClient mailClient;
User user;
@BeforeEach
void init(@Mock SettingRepository settingRepository) {
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
- lenient().when(settingRepository.getUserMinAge()).thenReturn(10);
+ lenient().when(settingRepository.getUserMinAge())
+ .thenReturn(10);
when(settingRepository.getUserNameMinLength()).thenReturn(4);
- lenient().when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(false);
+ lenient().when(userRepository.isUsernameAlreadyExists(any(String.class)))
+ .thenReturn(false);
this.settingRepository = settingRepository;
}
@@ -66,7 +73,7 @@ public class UserServiceUnitTest {
// Then
verify(userRepository).insert(user);
- Assertions.assertNotNull(user.getId());
+ assertNotNull(user.getId());
verify(mailClient).sendUserRegistrationMail(insertedUser);
}
@@ -80,7 +87,7 @@ public class UserServiceUnitTest {
userService.register(user);
fail("Should give an error");
} catch (Exception ex) {
- assertEquals(ex.getMessage(), Errors.USER_NAME_SHORT);
+ assertThat(ex.getMessage()).isEqualTo(Errors.USER_NAME_SHORT);
}
// Then
@@ -97,7 +104,7 @@ public class UserServiceUnitTest {
userService.register(user);
fail("Should give an error");
} catch (Exception ex) {
- assertEquals(ex.getMessage(), Errors.USER_AGE_YOUNG);
+ assertThat(ex.getMessage()).isEqualTo(Errors.USER_AGE_YOUNG);
}
// Then
@@ -116,7 +123,7 @@ public class UserServiceUnitTest {
userService.register(user);
fail("Should give an error");
} catch (Exception ex) {
- assertEquals(ex.getMessage(), Errors.USER_NAME_DUPLICATE);
+ assertThat(ex.getMessage()).isEqualTo(Errors.USER_NAME_DUPLICATE);
}
// Then
