Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added tests for custom exceptions #556

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.softserveinc.dokazovi.dto.payload.LoginRequest;
import com.softserveinc.dokazovi.entity.UserEntity;
import com.softserveinc.dokazovi.exception.BadRequestException;
import com.softserveinc.dokazovi.security.TokenProvider;
import com.softserveinc.dokazovi.service.ProviderService;
import com.softserveinc.dokazovi.service.UserService;
Expand All @@ -26,6 +27,8 @@

import static com.softserveinc.dokazovi.controller.EndPoints.AUTH;
import static com.softserveinc.dokazovi.controller.EndPoints.AUTH_LOGIN;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
Expand All @@ -51,50 +54,96 @@ class AuthControllerTest {
@InjectMocks
private AuthController authController;

private static final String EMAIL = "[email protected]";
private static final String PASSWORD = "user";
private static final String TOKEN = "950c9760-805e-449c-a966-2d0d5ebd86f4";
private static final String URI = AUTH + AUTH_LOGIN;
public static final String BAD_REQUEST_MESSAGE = "Please confirm your email!";

@BeforeEach
public void init() {
this.mockMvc = MockMvcBuilders
.standaloneSetup(authController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.build();
LoginRequest loginRequest = new LoginRequest();
loginRequest.setEmail(EMAIL);
loginRequest.setPassword(PASSWORD);
}

@Test
void loginUser() throws Exception {
String email = "[email protected]";
String password = "user";
LoginRequest loginRequest = createLoginRequest(EMAIL, PASSWORD);
Authentication authentication = authenticate(loginRequest);
V-Kaidash marked this conversation as resolved.
Show resolved Hide resolved
UserEntity user = buildUserEntity(EMAIL, PASSWORD, true);
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.thenReturn(authentication);
when(tokenProvider.createToken(authentication)).thenReturn(TOKEN);
when(userService.findByEmail(anyString())).thenReturn(user);
mockMvc.perform(MockMvcRequestBuilders.post(URI)
.content(asJsonString(loginRequest))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
assertEquals(TOKEN, tokenProvider.createToken(authentication));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That assertion doesn't make sense because it uses mocked value result from line 81 when(tokenProvider.createToken(authentication)).thenReturn(TOKEN);

You should compare TOKEN with value in the response after POST request. In your case, it will look like
mockMvc.perform(MockMvcRequestBuilders.post(URI) .content(asJsonString(loginRequest)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(mvcResult -> mvcResult.getResponse().getContentAsString().equals(TOKEN));

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

verify(authenticationManager, times(1))
.authenticate(any(UsernamePasswordAuthenticationToken.class));
verify(userService, times(1))
.findByEmail(anyString());
verify(tokenProvider, times(2))
.createToken(authentication);
}
V-Kaidash marked this conversation as resolved.
Show resolved Hide resolved

@Test
void loginUser_WhenEnabledFalse_ThrowException() throws Exception {
LoginRequest loginRequest = createLoginRequest(EMAIL, PASSWORD);
Authentication authentication = authenticate(loginRequest);
UserEntity user = buildUserEntity(EMAIL, PASSWORD, false);
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.thenReturn(authentication);
when(tokenProvider.createToken(any(Authentication.class))).thenReturn(TOKEN);
when(userService.findByEmail(anyString())).thenReturn(user);
mockMvc.perform(MockMvcRequestBuilders.post(URI)
.content(asJsonString(loginRequest))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(result ->
assertTrue(result.getResolvedException()
instanceof
BadRequestException))
.andExpect(result ->
assertEquals(
BAD_REQUEST_MESSAGE,
result.getResolvedException().getMessage()));
verify(userService, times(1))
.findByEmail(anyString());
}

private LoginRequest createLoginRequest(String email, String password) {
LoginRequest loginRequest = new LoginRequest();
loginRequest.setEmail(email);
loginRequest.setPassword(password);
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(

return loginRequest;
}

private Authentication authenticate(LoginRequest loginRequest) {
return new UsernamePasswordAuthenticationToken(
loginRequest.getEmail(),
loginRequest.getPassword()
)
);
String token = "950c9760-805e-449c-a966-2d0d5ebd86f4";
String uri = AUTH + AUTH_LOGIN;
UserEntity user = UserEntity.builder()
}

private UserEntity buildUserEntity(String email, String password, boolean enabled) {
return UserEntity.builder()
.email(email)
.password(password)
.enabled(true)
.enabled(enabled)
.build();
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.thenReturn(authentication);
when(tokenProvider.createToken(any(Authentication.class))).thenReturn(token);
when(userService.findByEmail(anyString())).thenReturn(user);
mockMvc.perform(MockMvcRequestBuilders.post(uri)
.content(asJsonString(loginRequest))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
verify(authenticationManager, times(2))
.authenticate(any(UsernamePasswordAuthenticationToken.class));
verify(userService, times(1))
.findByEmail(anyString());
}

public static String asJsonString(final Object obj) {
private String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.softserveinc.dokazovi.entity.RoleEntity;
import com.softserveinc.dokazovi.entity.UserEntity;
import com.softserveinc.dokazovi.entity.enumerations.UserStatus;
import com.softserveinc.dokazovi.exception.ResourceNotFoundException;
import com.softserveinc.dokazovi.repositories.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand All @@ -17,6 +18,8 @@
import java.util.Set;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
Expand All @@ -25,19 +28,12 @@
@ExtendWith(MockitoExtension.class)
class CustomUserDetailsServiceTest {

@Mock
private UserEntity userEntity;

@Mock
private UserRepository userRepository;

@Mock
private UserPrincipal userPrincipal;

@InjectMocks
private CustomUserDetailsService customUserDetailsService;


@Test
void loadUserByUsername() {
String email = "[email protected]";
Expand Down Expand Up @@ -83,4 +79,16 @@ void loadUserById() {
verify(userRepository, times(1)).findById(id);
assertEquals(email, resultUser.getUsername());
}

@Test
void loadUserById_UserNotFound_ThrowException() {
Integer id = 0;
Exception exception = assertThrows(ResourceNotFoundException.class, () ->
customUserDetailsService.loadUserById(id)
);
String expectedMessage = String.format("%s not found with %s : '%s'", "User", "id", id);
assertEquals(expectedMessage, exception.getMessage());
verify(userRepository, times(1))
.findById(any(Integer.class));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
Expand Down Expand Up @@ -1278,6 +1279,78 @@ void updatePostById_WhenExists_isOk_DoctorRole() {
Assertions.assertThat(postService.updatePostById(userPrincipal, dto)).isTrue();
}

@Test
void updatePostById_WhenPostStatus_NotFound_ThrowException() {
Set<RolePermission> permissions = new HashSet<>();
permissions.add(RolePermission.DELETE_OWN_POST);

RoleEntity roleEntity = new RoleEntity();
roleEntity.setId(3);
roleEntity.setName("Doctor");
roleEntity.setPermissions(permissions);

PostTypeIdOnlyDTO postTypeDTO = new PostTypeIdOnlyDTO();
postTypeDTO.setId(1);

DirectionDTOForSavingPost directionDTO = new DirectionDTOForSavingPost();
directionDTO.setId(1);

Set<@DirectionExists DirectionDTOForSavingPost> directions = new HashSet<>();
directions.add(directionDTO);

OriginDTOForSavingPost originDTO = new OriginDTOForSavingPost();
originDTO.setId(1);

Set<@OriginExists OriginDTOForSavingPost> origins = new HashSet<>();
origins.add(originDTO);

UserPrincipal userPrincipal = UserPrincipal.builder()
.id(38)
.email("[email protected]")
.password("$2a$10$ubeFvFhz0/P5js292OUaee9QxaBsI7cvoAmSp1inQ0MxI/gxazs8O")
.role(roleEntity)
.build();

UserEntity doctorUserEntity = UserEntity.builder()
.id(38)
.email("[email protected]")
.password("$2a$10$ubeFvFhz0/P5js292OUaee9QxaBsI7cvoAmSp1inQ0MxI/gxazs8O")
.role(roleEntity)
.build();

PostSaveFromUserDTO dto = PostSaveFromUserDTO.builder()
.id(1)
.authorId(1)
.title("title")
.videoUrl("videoUrl")
.previewImageUrl("previewImageUrl")
.preview("preview")
.content("content")
.type(postTypeDTO)
.directions(directions)
.origins(origins)
.postStatus(3)
.build();

Integer id = 1;
PostEntity postEntity = PostEntity
.builder()
.id(id)
.author(doctorUserEntity)
.build();

when(postMapper.updatePostEntityFromDTO(dto, postEntity)).thenReturn(postEntity);
when(postRepository.findById(any(Integer.class))).thenReturn(Optional.of(postEntity));
Exception exception = assertThrows(ForbiddenPermissionsException.class, () ->
postService.updatePostById(userPrincipal, dto)
);
String expectedMessage = "Forbidden permission";
assertEquals(expectedMessage, exception.getMessage());
verify(postRepository, never())
.save(any(PostEntity.class)
);
}

@Test
void archivePostById_WhenExists_isOk_DoctorRole() {
Set<RolePermission> permissions = new HashSet<>();
Expand Down Expand Up @@ -1723,4 +1796,29 @@ void setPublishedAtTest() {
Mockito.when(postRepository.findById(1)).thenReturn(Optional.of(postEntity));
assertTrue(postService.setPublishedAt(1, postPublishedAtDTO));
}

@Test
void setPublishedAt_WhenPost_NotFound_ThrowException() {
Integer postId = 0;
Timestamp publishedAt = Timestamp.valueOf(
LocalDateTime.of(
LocalDate.of(2002, Month.JANUARY, 14),
LocalTime.MIN)
);
PostPublishedAtDTO postPublishedAtDTO = PostPublishedAtDTO
.builder()
.publishedAt(publishedAt)
.build();
Exception exception = assertThrows(EntityNotFoundException.class, () ->
postService.setPublishedAt(postId, postPublishedAtDTO)
);
String expectedMessage = "Post with this id=" + postId + " doesn't exist";
assertEquals(expectedMessage, exception.getMessage());
verify(postRepository, times(1))
.findById(any(Integer.class));
verify(postRepository, never())
.setPublishedAt(any(Integer.class), any(Timestamp.class));
verify(postRepository, never())
.save(any(PostEntity.class));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
Expand Down Expand Up @@ -359,6 +360,21 @@ void setEnableTrue() {
.findById(any(Integer.class));
}

@Test
void setEnableTrue_WhenNotFound_ThrowException() {
UserEntity userEntity = UserEntity.builder()
.id(0)
.build();
Exception exception = assertThrows(BadRequestException.class, () ->
userService.setEnableTrue(userEntity));
String expectedMessage = "Something went wrong!!!";
assertEquals(expectedMessage, exception.getMessage());
verify(userRepository, times(1))
.findById(any(Integer.class));
verify(userRepository, never())
.save(userEntity);
}

@Test
void getVerificationToken() {
String token = "950c9760-805e-449c-a966-2d0d5ebd86f4";
Expand Down