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

Controller tests #55

Merged
merged 6 commits into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
118 changes: 118 additions & 0 deletions src/test/java/com/linkurlshorter/urlshortener/TestConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package com.linkurlshorter.urlshortener;

import com.linkurlshorter.urlshortener.auth.AuthService;
import com.linkurlshorter.urlshortener.jwt.JwtUtil;
import com.linkurlshorter.urlshortener.link.LinkInfoDtoMapper;
import com.linkurlshorter.urlshortener.link.LinkRepository;
import com.linkurlshorter.urlshortener.link.LinkService;
import com.linkurlshorter.urlshortener.security.CustomUserDetailsService;
import com.linkurlshorter.urlshortener.user.UserRepository;
import com.linkurlshorter.urlshortener.user.UserService;
import jakarta.persistence.EntityManager;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;

import static org.mockito.Mockito.mock;

/**
* Configuration class for test environment.
* Provides bean definitions for mocked services and repositories used in testing.
*
* @author Anastasiia Usenko
*/
@TestConfiguration
public class TestConfig {

/**
* Creates a mock bean for JwtUtil.
*
* @return JwtUtil mock bean
*/
@Bean
public JwtUtil jwtUtil() {
return new JwtUtil();
}

/**
* Creates a bean for CustomUserDetailsService with a mocked UserService dependency.
*
* @param userService UserService mock bean
* @return CustomUserDetailsService bean with mocked UserService dependency
*/
@Bean
public CustomUserDetailsService customUserDetailsService(UserService userService) {
return new CustomUserDetailsService(userService);
}

/**
* Creates a bean for LinkInfoDtoMapper.
*
* @return LinkInfoDtoMapper bean
*/
@Bean
public LinkInfoDtoMapper linkInfoDtoMapper() {
return new LinkInfoDtoMapper();
}

/**
* Creates a mock bean for EntityManager.
*
* @return EntityManager mock bean
*/
@Bean
public EntityManager entityManager() {
return mock(EntityManager.class);
}

/**
* Creates a bean for LinkService with a mocked LinkRepository dependency.
*
* @param linkRepository LinkRepository mock bean
* @return LinkService bean with mocked LinkRepository dependency
*/
@Bean
public LinkService linkService(LinkRepository linkRepository) {
return new LinkService(linkRepository);
}

/**
* Creates a bean for UserService with a mocked UserRepository dependency.
*
* @param userRepository UserRepository mock bean
* @return UserService bean with mocked UserRepository dependency
*/
@Bean
public UserService userService(UserRepository userRepository) {
return new UserService(userRepository);
}

/**
* Creates a mock bean for LinkRepository.
*
* @return LinkRepository mock bean
*/
@Bean
public LinkRepository linkRepository() {
return mock(LinkRepository.class);
}

/**
* Creates a mock bean for UserRepository.
*
* @return UserRepository mock bean
*/
@Bean
public UserRepository userRepository() {
return mock(UserRepository.class);
}

/**
* Creates a mock bean for AuthService.
*
* @return AuthService mock bean
*/
@Bean
public AuthService authService() {
return mock(AuthService.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,57 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkurlshorter.urlshortener.auth.dto.AuthRequest;
import com.linkurlshorter.urlshortener.auth.exception.EmailAlreadyTakenException;
import com.linkurlshorter.urlshortener.TestConfig;
import com.linkurlshorter.urlshortener.security.SecurityConfig;
import com.linkurlshorter.urlshortener.security.UnauthorizedException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;

import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Unit tests for {@link AuthController} class.
*
* @author Anastasiia Usenko
*/
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@ExtendWith(MockitoExtension.class)
@WebMvcTest(controllers = AuthController.class)
@Import({SecurityConfig.class, TestConfig.class})
class AuthControllerTest {


@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper;

@MockBean
private AuthService authService;

/**
* Test case for the {@link AuthController#register(AuthRequest)} method.
*/
@Test
void registrationSuccessfulTest() throws Exception {
AuthRequest request = new AuthRequest("[email protected]", "Password1");
performRegistration(request)
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("User registered successfully!"))
.andExpect(MockMvcResultMatchers.jsonPath("$.jwtToken").exists());
when(authService.registerUser(request)).thenReturn(String.valueOf(request));

ResultActions resultActions = mockMvc.perform(post("/api/V1/auth/register")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)));

resultActions.andExpect(jsonPath("$.message").value("User registered successfully!"))
.andExpect(jsonPath("$.jwtToken").exists());
}

/**
Expand All @@ -54,12 +62,13 @@ void registrationSuccessfulTest() throws Exception {
@Test
void registrationFailedTest() throws Exception {
AuthRequest request = new AuthRequest("[email protected]", "Password1");
performRegistration(request)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("User registered successfully!"))
.andExpect(MockMvcResultMatchers.jsonPath("$.jwtToken").exists());
when(authService.registerUser(request)).thenThrow(EmailAlreadyTakenException.class);

performRegistration(request).andExpect(MockMvcResultMatchers.status().isBadRequest());
ResultActions resultActions = mockMvc.perform(post("/api/V1/auth/register")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)));

resultActions.andExpect(status().isBadRequest());
}

/**
Expand All @@ -68,12 +77,15 @@ void registrationFailedTest() throws Exception {
@Test
void loginSuccessfulTest() throws Exception {
AuthRequest request = new AuthRequest("[email protected]", "Password1");
performRegistration(request).andExpect(MockMvcResultMatchers.status().isOk());
when(authService.loginUser(request)).thenReturn(String.valueOf(request));

performLogin(request)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("User logged in successfully!"))
.andExpect(MockMvcResultMatchers.jsonPath("$.jwtToken").exists());
ResultActions resultActions = mockMvc.perform(post("/api/V1/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)));

resultActions.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("User logged in successfully!"))
.andExpect(jsonPath("$.jwtToken").exists());
}

/**
Expand All @@ -82,32 +94,12 @@ void loginSuccessfulTest() throws Exception {
@Test
void loginFailedTest() throws Exception {
AuthRequest request = new AuthRequest("[email protected]", "Password1");
performLogin(request).andExpect(MockMvcResultMatchers.status().isUnauthorized());
}
when(authService.loginUser(request)).thenThrow(UnauthorizedException.class);

/**
* Performs registration request.
*
* @param request the registration request
* @return the result actions after performing registration
* @throws Exception if an error occurs during the registration process
*/
private ResultActions performRegistration(AuthRequest request) throws Exception {
return mockMvc.perform(post("/api/V1/auth/register")
ResultActions resultActions = mockMvc.perform(post("/api/V1/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)));
}

/**
* Performs login request.
*
* @param request the login request
* @return the result actions after performing login
* @throws Exception if an error occurs during the login process
*/
private ResultActions performLogin(AuthRequest request) throws Exception {
return mockMvc.perform(post("/api/V1/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)));
resultActions.andExpect(status().isUnauthorized());
}
}
}
Loading
Loading