Skip to content

Commit

Permalink
Cleaned up tests with @ExtendWith(MockitoExtension.class)
Browse files Browse the repository at this point in the history
  • Loading branch information
roar-skinderviken committed Feb 6, 2025
1 parent dd1d12d commit f3a6696
Show file tree
Hide file tree
Showing 9 changed files with 68 additions and 115 deletions.
Original file line number Diff line number Diff line change
@@ -1,39 +1,28 @@
package no.vicx.authserver;

import no.vicx.database.user.VicxUser;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.stream.Stream;

import static no.vicx.authserver.CustomUserDetails.*;
import static no.vicx.authserver.UserTestUtils.*;
import static no.vicx.authserver.UserTestUtils.createUserImageInTest;
import static no.vicx.authserver.UserTestUtils.createUserInTest;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.openMocks;

@ExtendWith(MockitoExtension.class)
class CustomUserDetailsTest {

@Mock
VicxUser user;

AutoCloseable openMocks;

@BeforeEach
void setUp() {
openMocks = openMocks(this);
}

@AfterEach
void tearDown() throws Exception {
openMocks.close();
}

@ParameterizedTest
@MethodSource("invalidParametersSource")
void constructor_givenInvalidParameters_expectException(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package no.vicx.authserver.config;

import no.vicx.authserver.CustomUserDetails;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
Expand All @@ -20,8 +20,8 @@

import static no.vicx.authserver.config.JwtCustomizerConfig.*;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.openMocks;

@ExtendWith(MockitoExtension.class)
class JwtCustomizerConfigTest {

@Mock
Expand All @@ -38,32 +38,11 @@ class JwtCustomizerConfigTest {

OAuth2TokenCustomizer<JwtEncodingContext> sut;

AutoCloseable openMocks;

@BeforeEach
void setUp() {
openMocks = openMocks(this);
sut = new JwtCustomizerConfig().jwtCustomizer();

when(context.getPrincipal()).thenReturn(authentication);
when(context.getAuthorizedScopes()).thenReturn(Set.of(OidcScopes.PROFILE, OidcScopes.EMAIL));
when(context.getClaims()).thenReturn(claimsBuilder);

when(authentication.getPrincipal()).thenReturn(customUserDetails);
doReturn(List.of(
new SimpleGrantedAuthority("USER"),
new SimpleGrantedAuthority("ADMIN")
)).when(authentication).getAuthorities();

when(customUserDetails.getUsername()).thenReturn("john-doe");
when(customUserDetails.getName()).thenReturn("John Doe");
when(customUserDetails.getEmail()).thenReturn("[email protected]");
when(customUserDetails.hasImage()).thenReturn(true);
}

@AfterEach
void tearDown() throws Exception {
openMocks.close();
}

@Test
Expand All @@ -78,6 +57,12 @@ void customize_givenNullPrincipal_expectNoClaimsToBeSet() {
@Test
void customize_givenContextForAccessToken_expectOnlyRolesClaimToBeSet() {
when(context.getTokenType()).thenReturn(OAuth2TokenType.ACCESS_TOKEN);
when(context.getClaims()).thenReturn(claimsBuilder);

doReturn(List.of(
new SimpleGrantedAuthority("USER"),
new SimpleGrantedAuthority("ADMIN")
)).when(authentication).getAuthorities();

sut.customize(context);

Expand All @@ -89,11 +74,8 @@ void customize_givenContextForAccessToken_expectOnlyRolesClaimToBeSet() {

@Test
void customize_givenPrincipalDifferentFromCustomUserDetails_expectOnlyRolesClaimToBeSet() {
when(authentication.getPrincipal()).thenReturn(new User(
"username",
"password",
List.of(new SimpleGrantedAuthority("USER"))
));
when(context.getTokenType()).thenReturn(OAuth2TokenType.ACCESS_TOKEN);
when(context.getClaims()).thenReturn(claimsBuilder);
doReturn(List.of(new SimpleGrantedAuthority("USER"))).when(authentication).getAuthorities();

sut.customize(context);
Expand All @@ -106,7 +88,12 @@ void customize_givenPrincipalDifferentFromCustomUserDetails_expectOnlyRolesClaim

@Test
void customize_givenNoScopes_expectOnlyRolesClaimToBeSet() {
when(context.getAuthorizedScopes()).thenReturn(Collections.emptySet());
when(context.getTokenType()).thenReturn(OAuth2TokenType.ACCESS_TOKEN);
when(context.getClaims()).thenReturn(claimsBuilder);
doReturn(List.of(
new SimpleGrantedAuthority("USER"),
new SimpleGrantedAuthority("ADMIN")
)).when(authentication).getAuthorities();

sut.customize(context);

Expand All @@ -119,6 +106,14 @@ void customize_givenNoScopes_expectOnlyRolesClaimToBeSet() {

@Test
void customize_givenUserDetailsWithoutImage_expectImageClaimNotToBeSet() {
when(context.getAuthorizedScopes()).thenReturn(Set.of(OidcScopes.PROFILE, OidcScopes.EMAIL));
when(context.getClaims()).thenReturn(claimsBuilder);
when(authentication.getPrincipal()).thenReturn(customUserDetails);
doReturn(List.of(new SimpleGrantedAuthority("USER"))).when(authentication).getAuthorities();

when(customUserDetails.hasImage()).thenReturn(false);
when(customUserDetails.getName()).thenReturn("John Doe");
when(customUserDetails.getEmail()).thenReturn("[email protected]");
when(customUserDetails.hasImage()).thenReturn(false);

sut.customize(context);
Expand All @@ -128,6 +123,19 @@ void customize_givenUserDetailsWithoutImage_expectImageClaimNotToBeSet() {

@Test
void customize_givenUserDetailsWithAllPropsSet_expectAllClaimsToBeSet() {
when(context.getAuthorizedScopes()).thenReturn(Set.of(OidcScopes.PROFILE, OidcScopes.EMAIL));
when(context.getClaims()).thenReturn(claimsBuilder);
when(authentication.getPrincipal()).thenReturn(customUserDetails);
doReturn(List.of(
new SimpleGrantedAuthority("USER"),
new SimpleGrantedAuthority("ADMIN")
)).when(authentication).getAuthorities();

when(customUserDetails.getUsername()).thenReturn("john-doe");
when(customUserDetails.getName()).thenReturn("John Doe");
when(customUserDetails.getEmail()).thenReturn("[email protected]");
when(customUserDetails.hasImage()).thenReturn(true);

sut.customize(context);

verify(claimsBuilder).claim(ROLES_CLAIM, List.of("USER", "ADMIN"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
import no.vicx.authserver.CustomUserDetails;
import no.vicx.database.user.UserRepository;
import no.vicx.database.user.VicxUser;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
Expand All @@ -18,8 +19,8 @@
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.openMocks;

@ExtendWith(MockitoExtension.class)
class UserDetailsConfigTest {

@Mock
Expand All @@ -32,28 +33,18 @@ class UserDetailsConfigTest {

UserDetailsService userDetailsService;

AutoCloseable openMocks;

@BeforeEach
void setUp() {
openMocks = openMocks(this);

when(passwordEncoder.encode(anyString())).thenReturn("~encoded-password~");

userInTest = createUserInTest(null);
when(userRepository.findByUsername(EXISTING_USERNAME)).thenReturn(Optional.of(userInTest));

userDetailsService = new UserDetailsConfig().userDetailsService(
DEFAULT_USER_PROPERTIES, passwordEncoder, userRepository);
}

@AfterEach
void tearDown() throws Exception {
openMocks.close();
}

@Test
void loadUserByUsername_givenUsernameForDefaultUser_expectDefaultUser() {
when(passwordEncoder.encode(anyString())).thenReturn("~encoded-password~");

var defaultUser = (CustomUserDetails) userDetailsService.loadUserByUsername(DEFAULT_USERNAME_IN_TEST);

assertEquals(DEFAULT_USER_PROPERTIES.username(), defaultUser.getUsername());
Expand All @@ -68,13 +59,16 @@ void loadUserByUsername_givenUsernameForDefaultUser_expectDefaultUser() {

@Test
void loadUserByUsername_givenUsernameForDefaultUserInUpperCase_expectDefaultUser() {
when(passwordEncoder.encode(anyString())).thenReturn("~encoded-password~");
var defaultUser = userDetailsService.loadUserByUsername(DEFAULT_USERNAME_IN_TEST.toUpperCase());

assertEquals(DEFAULT_USERNAME_IN_TEST, defaultUser.getUsername());
}

@Test
void loadUserByUsername_givenUsernameForExistingUser_expectUser() {
when(userRepository.findByUsername(EXISTING_USERNAME)).thenReturn(Optional.of(userInTest));

var userDetails = userDetailsService.loadUserByUsername(EXISTING_USERNAME);

assertInstanceOf(CustomUserDetails.class, userDetails);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
import no.vicx.database.calculator.CalcEntry;
import no.vicx.database.calculator.CalculatorOperation;
import no.vicx.database.calculator.CalculatorRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
Expand All @@ -24,28 +25,20 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.openMocks;

@ExtendWith(MockitoExtension.class)
class CalculatorServiceTest {

@Mock
CalculatorRepository calculatorRepository;

CalculatorService sut;

AutoCloseable openMocks;

@BeforeEach
void setUp() {
openMocks = openMocks(this);
sut = new CalculatorService(calculatorRepository, Duration.ZERO);
}

@AfterEach
void tearDown() throws Exception {
openMocks.close();
}

@ParameterizedTest
@ValueSource(booleans = {true, false})
void getAllCalculations_givenDataInDatabase_expectPageWithCalculations(boolean addPage) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
import no.vicx.backend.esport.vm.EsportTeamVm;
import no.vicx.backend.esport.vm.MatchType;
import no.vicx.backend.esport.vm.OpponentVm;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
Expand All @@ -24,33 +25,24 @@

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.openMocks;

@ExtendWith(MockitoExtension.class)
class EsportClientTest {

@Mock
ExchangeFunction exchangeFunction;

EsportClient sut;

AutoCloseable openMocks;

@BeforeEach
void setUp() {
openMocks = openMocks(this);

WebClient webClient = WebClient.builder()
.exchangeFunction(exchangeFunction)
.build();

sut = new EsportClient(webClient, "~token~");
}

@AfterEach
void tearDown() throws Exception {
openMocks.close();
}

private static final ObjectMapper MAPPER = new ObjectMapper();

@Test
Expand Down
Loading

0 comments on commit f3a6696

Please sign in to comment.