Compare commits
19 Commits
edeb36cb8c
...
c59998c113
| Author | SHA1 | Date | |
|---|---|---|---|
| c59998c113 | |||
| ff5dc5c090 | |||
| 4d7a191e8a | |||
| 7c7e82b0e6 | |||
| 7d070075d6 | |||
| b24d263f22 | |||
| f7023f9c4a | |||
| cad54d7b96 | |||
| b124a4b0e8 | |||
| 6e318a07c6 | |||
| b476f2e8c9 | |||
| 5d7ab8d45d | |||
| 5addf38127 | |||
| a5bc401e89 | |||
| dfa747f548 | |||
| f9f2bff77e | |||
| 3d064e0496 | |||
| 3b9b0769d1 | |||
| 3e5baa34d1 |
@@ -3,6 +3,7 @@ package _11.asktpk.artisanconnectbackend.controller;
|
||||
import _11.asktpk.artisanconnectbackend.customExceptions.ClientAlreadyExistsException;
|
||||
import _11.asktpk.artisanconnectbackend.customExceptions.WrongLoginPasswordException;
|
||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
||||
import _11.asktpk.artisanconnectbackend.service.AuthService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -16,9 +17,10 @@ import org.springframework.web.client.HttpClientErrorException;
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
public AuthController(AuthService authService) {
|
||||
private final JwtUtil jwtUtil;
|
||||
public AuthController(AuthService authService, JwtUtil jwtUtil) {
|
||||
this.authService = authService;
|
||||
this.jwtUtil = jwtUtil;
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
@@ -94,4 +96,14 @@ public class AuthController {
|
||||
.body(new RequestResponseDTO("Authentication Error (Google): " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public ResponseEntity<?> getMe(HttpServletRequest request) {
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(new AuthResponseDTO(jwtUtil.extractUserId(token), jwtUtil.extractRole(token), token));
|
||||
}
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Invalid or empty token"));
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,441 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.NoticeRepository;
|
||||
import _11.asktpk.artisanconnectbackend.service.*;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.http.*;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Image;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ImageRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@SpringBootTest
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.Comparator;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Testy dla funkcjonalności klienta w backendzie.
|
||||
*/
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
class ArtisanConnectBackendApplicationTests {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(ArtisanConnectBackendApplicationTests.class);
|
||||
|
||||
// @Test
|
||||
// void testPostgresDatabase() {
|
||||
// postgresDatabase.add(new Notice("Test Notice", "Username", "Test Description"));
|
||||
// Boolean isRecordAvailable = postgresDatabase.get().size() > 0;
|
||||
// if(isRecordAvailable) {
|
||||
// logger.info("The record is available in the database");
|
||||
// } else {
|
||||
// logger.error("The record is not available in the database");
|
||||
// }
|
||||
// assert isRecordAvailable;
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// void getAllNotices() throws IOException {
|
||||
// OkHttpClient client = new OkHttpClient().newBuilder()
|
||||
// .build();
|
||||
// MediaType mediaType = MediaType.parse("text/plain");
|
||||
// Request request = new Request.Builder()
|
||||
// .url("http://localhost:8080/api/v1/notices/all")
|
||||
// .build();
|
||||
// Response response = client.newCall(request).execute();
|
||||
// }
|
||||
}
|
||||
@Nested
|
||||
@DisplayName("Testy integracyjne ImageService")
|
||||
class ImageServiceTest {
|
||||
|
||||
private final Logger logger = LogManager.getLogger(ImageServiceTest.class);
|
||||
private final ImageService imageService;
|
||||
private final ImageRepository imageRepository;
|
||||
private final Path testDirectory;
|
||||
|
||||
ImageServiceTest() throws Exception {
|
||||
logger.info("Inicjalizacja testów ImageService");
|
||||
this.imageRepository = mock(ImageRepository.class);
|
||||
this.testDirectory = Files.createTempDirectory("test-images");
|
||||
logger.info("Utworzono katalog testowy: {}", testDirectory);
|
||||
|
||||
Constructor<ImageService> constructor = ImageService.class.getDeclaredConstructor(ImageRepository.class);
|
||||
constructor.setAccessible(true);
|
||||
this.imageService = constructor.newInstance(imageRepository);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() throws IOException {
|
||||
logger.info("Sprzątanie po teście - usuwanie katalogu testowego: {}", testDirectory);
|
||||
try (var paths = Files.walk(testDirectory)) {
|
||||
paths.sorted(Comparator.reverseOrder())
|
||||
.forEach(path -> {
|
||||
try {
|
||||
Files.delete(path);
|
||||
logger.debug("Usunięto plik: {}", path);
|
||||
} catch (IOException e) {
|
||||
logger.warn("Nie można usunąć pliku: {}", path, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie zapisać obraz w magazynie plików")
|
||||
void shouldSaveImageToStorage() throws IOException {
|
||||
logger.info("Test zapisu obrazu - rozpoczęcie");
|
||||
|
||||
final String testFileName = "test.jpg";
|
||||
final Path testFilePath = testDirectory.resolve(testFileName);
|
||||
Files.createFile(testFilePath);
|
||||
Files.write(testFilePath, "test content".getBytes());
|
||||
logger.debug("Utworzono testowy plik: {}", testFilePath);
|
||||
|
||||
final MultipartFile file = mock(MultipartFile.class);
|
||||
when(file.getOriginalFilename()).thenReturn(testFileName);
|
||||
when(file.getInputStream()).thenReturn(Files.newInputStream(testFilePath));
|
||||
|
||||
final String savedFileName = imageService.saveImageToStorage(testDirectory.toString(), file);
|
||||
logger.info("Zapisano plik pod nazwą: {}", savedFileName);
|
||||
|
||||
assertTrue(savedFileName.endsWith(".jpg"));
|
||||
assertTrue(Files.exists(testDirectory.resolve(savedFileName)));
|
||||
logger.info("Test zapisu obrazu - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie pobrać obraz")
|
||||
void shouldGetImage() throws IOException {
|
||||
logger.info("Test pobierania obrazu - rozpoczęcie");
|
||||
|
||||
final String testFileName = "test.jpg";
|
||||
Files.createFile(testDirectory.resolve(testFileName));
|
||||
logger.debug("Utworzono testowy plik: {}", testFileName);
|
||||
|
||||
final Resource resource = imageService.getImage(testDirectory.toString(), testFileName);
|
||||
logger.info("Pobrano zasób: {}", resource.getFilename());
|
||||
|
||||
assertNotNull(resource);
|
||||
assertTrue(resource.exists());
|
||||
assertInstanceOf(UrlResource.class, resource);
|
||||
logger.info("Test pobierania obrazu - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zgłosić błąd, gdy obraz nie zostanie znaleziony")
|
||||
void shouldThrowExceptionWhenImageNotFound() {
|
||||
logger.info("Test obsługi błędu - rozpoczęcie");
|
||||
|
||||
final Exception exception = assertThrows(IOException.class, () ->
|
||||
imageService.getImage(testDirectory.toString(), "missing.jpg")
|
||||
);
|
||||
logger.info("Złapano wyjątek: {}", exception.getMessage());
|
||||
|
||||
assertThat(exception).hasMessageContaining("File not found");
|
||||
logger.info("Test obsługi błędu - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie usuwać obraz z magazynu plików")
|
||||
void shouldDeleteImage() throws IOException {
|
||||
logger.info("Test usuwania obrazu - rozpoczęcie");
|
||||
|
||||
final String testFileName = "test-delete.jpg";
|
||||
final Path testFilePath = testDirectory.resolve(testFileName);
|
||||
Files.createFile(testFilePath);
|
||||
logger.debug("Utworzono testowy plik: {}", testFilePath);
|
||||
|
||||
when(imageRepository.existsImageByImageNameEqualsIgnoreCase(testFileName)).thenReturn(true);
|
||||
|
||||
imageService.deleteImage(testDirectory.toString(), testFileName);
|
||||
logger.info("Usunięto plik: {}", testFileName);
|
||||
|
||||
assertFalse(Files.exists(testFilePath));
|
||||
verify(imageRepository).deleteByImageNameEquals(testFileName);
|
||||
logger.info("Test usuwania obrazu - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie zwrócić listę nazw obrazów")
|
||||
void shouldGetImagesListForNotice() throws Exception {
|
||||
logger.info("Test pobierania listy obrazów - rozpoczęcie");
|
||||
|
||||
final Long noticeId = 1L;
|
||||
final List<String> expectedNames = List.of("image1.jpg", "image2.jpg");
|
||||
final List<Image> mockImages = expectedNames.stream()
|
||||
.map(name -> {
|
||||
Image img = new Image();
|
||||
img.setImageName(name);
|
||||
return img;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
when(imageRepository.findByNoticeId(noticeId)).thenReturn(mockImages);
|
||||
logger.debug("Skonfigurowano mock repository dla noticeId: {}", noticeId);
|
||||
|
||||
final List<String> imageNames = imageService.getImagesList(noticeId);
|
||||
logger.info("Pobrano listę {} obrazów", imageNames.size());
|
||||
|
||||
assertThat(imageNames).containsExactlyElementsOf(expectedNames);
|
||||
logger.info("Test pobierania listy obrazów - zakończony pomyślnie");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Nested
|
||||
@DisplayName("Testy dla VariablesController")
|
||||
@Transactional
|
||||
class VariablesControllerTest {
|
||||
|
||||
private final int port;
|
||||
private final TestRestTemplate restTemplate;
|
||||
|
||||
@Autowired
|
||||
public VariablesControllerTest(@LocalServerPort int port, TestRestTemplate restTemplate) {
|
||||
this.port = port;
|
||||
this.restTemplate = restTemplate;
|
||||
logger.info("Inicjalizacja testów VariablesController");
|
||||
}
|
||||
|
||||
private String registerAndGetJwtToken(String emailPrefix) {
|
||||
logger.info("Rozpoczęcie procesu rejestracji dla prefiksu email: {}", emailPrefix);
|
||||
String email = emailPrefix + "_" + UUID.randomUUID().toString().substring(0, 8) + "@example.com";
|
||||
logger.debug("Wygenerowany email: {}", email);
|
||||
|
||||
ClientRegistrationDTO registrationDTO = new ClientRegistrationDTO();
|
||||
registrationDTO.setEmail(email);
|
||||
registrationDTO.setFirstName("Test");
|
||||
registrationDTO.setLastName("User");
|
||||
registrationDTO.setPassword("password123");
|
||||
|
||||
ResponseEntity<AuthResponseDTO> response = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/register"),
|
||||
registrationDTO,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
|
||||
if (response.getStatusCode() == HttpStatus.CONFLICT) {
|
||||
logger.warn("Użytkownik już istnieje, próba logowania");
|
||||
AuthRequestDTO loginRequest = new AuthRequestDTO();
|
||||
loginRequest.setEmail(email);
|
||||
loginRequest.setPassword("password123");
|
||||
|
||||
response = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/login"),
|
||||
loginRequest,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
} else {
|
||||
logger.info("Pomyślnie zarejestrowano nowego użytkownika");
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
assertThat(response.getBody()).isNotNull();
|
||||
logger.debug("Otrzymano token JWT");
|
||||
return response.getBody().getToken();
|
||||
}
|
||||
|
||||
private HttpEntity<Void> createRequestWithToken(String token) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("Authorization", "Bearer " + token);
|
||||
return new HttpEntity<>(headers);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić kategorie")
|
||||
void shouldGetCategories() {
|
||||
logger.info("Test pobierania kategorii - rozpoczęcie");
|
||||
String token = registerAndGetJwtToken(
|
||||
"categories"
|
||||
);
|
||||
logger.debug("Otrzymano token autoryzacyjny");
|
||||
|
||||
String url = createURLWithPort("/api/v1/vars/categories");
|
||||
logger.debug("Utworzono URL endpointu: {}", url);
|
||||
|
||||
HttpEntity<Void> request = createRequestWithToken(token);
|
||||
ResponseEntity<CategoriesDTO[]> response = restTemplate.exchange(
|
||||
url,
|
||||
HttpMethod.GET,
|
||||
request,
|
||||
CategoriesDTO[].class
|
||||
);
|
||||
logger.info("Wykonano zapytanie o kategorie");
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull().isNotEmpty();
|
||||
logger.info("Test pobierania kategorii - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić statusy")
|
||||
void shouldGetStatuses() {
|
||||
String token = registerAndGetJwtToken(
|
||||
"statuses"
|
||||
);
|
||||
|
||||
String url = createURLWithPort("/api/v1/vars/statuses");
|
||||
|
||||
HttpEntity<Void> request = createRequestWithToken(token);
|
||||
ResponseEntity<Enums.Status[]> response = restTemplate.exchange(
|
||||
url,
|
||||
HttpMethod.GET,
|
||||
request,
|
||||
Enums.Status[].class
|
||||
);
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull().isNotEmpty();
|
||||
}
|
||||
|
||||
|
||||
private String createURLWithPort(String uri) {
|
||||
return "http://localhost:" + port + uri;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Nested
|
||||
@DisplayName("Testy integracyjne AuthController")
|
||||
@Transactional
|
||||
class AuthControllerTest {
|
||||
|
||||
private final int port;
|
||||
private final TestRestTemplate restTemplate;
|
||||
private final ClientRepository clientRepository;
|
||||
private final NoticeRepository noticeRepository;
|
||||
private final Logger logger = LogManager.getLogger(AuthControllerTest.class);
|
||||
|
||||
@Autowired
|
||||
public AuthControllerTest(
|
||||
@LocalServerPort int port,
|
||||
TestRestTemplate restTemplate,
|
||||
ClientRepository clientRepository,
|
||||
NoticeRepository noticeRepository) {
|
||||
this.port = port;
|
||||
this.restTemplate = restTemplate;
|
||||
this.clientRepository = clientRepository;
|
||||
this.noticeRepository = noticeRepository;
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void cleanDatabase() {
|
||||
noticeRepository.deleteAll();
|
||||
clientRepository.deleteAll();
|
||||
}
|
||||
|
||||
private String createURLWithPort(String uri) {
|
||||
return "http://localhost:" + port + uri;
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić błąd przy rejestracji z istniejącym emailem")
|
||||
void shouldFailRegisterWithExistingEmail() {
|
||||
String email = "user_" + UUID.randomUUID().toString().substring(0, 8) + "@example.com";
|
||||
ClientRegistrationDTO registrationDTO = new ClientRegistrationDTO();
|
||||
registrationDTO.setEmail(email);
|
||||
registrationDTO.setFirstName("Jan");
|
||||
registrationDTO.setLastName("Kowalski");
|
||||
registrationDTO.setPassword("password123");
|
||||
|
||||
ResponseEntity<AuthResponseDTO> firstResponse = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/register"),
|
||||
registrationDTO,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
assertThat(firstResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED);
|
||||
|
||||
ResponseEntity<AuthResponseDTO> secondResponse = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/register"),
|
||||
registrationDTO,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
logger.info("Wysłano żądanie rejestracji");
|
||||
|
||||
assertThat(secondResponse.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie zalogować istniejącego użytkownika")
|
||||
void shouldLoginExistingUser() {
|
||||
logger.info("Test logowania użytkownika - rozpoczęcie");
|
||||
String email = "user_" + UUID.randomUUID().toString().substring(0, 8) + "@example.com";
|
||||
String password = "password123";
|
||||
|
||||
ClientRegistrationDTO registrationDTO = new ClientRegistrationDTO();
|
||||
registrationDTO.setEmail(email);
|
||||
registrationDTO.setFirstName("Jan");
|
||||
registrationDTO.setLastName("Kowalski");
|
||||
registrationDTO.setPassword(password);
|
||||
restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/register"),
|
||||
registrationDTO,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
logger.debug("Zarejestrowano testowego użytkownika: {}", email);
|
||||
|
||||
AuthRequestDTO loginRequest = new AuthRequestDTO();
|
||||
loginRequest.setEmail(email);
|
||||
loginRequest.setPassword(password);
|
||||
|
||||
ResponseEntity<AuthResponseDTO> response = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/login"),
|
||||
loginRequest,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
logger.info("Wykonano próbę logowania");
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull();
|
||||
assertThat(response.getBody().getToken()).isNotBlank();
|
||||
logger.info("Test logowania - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić błąd przy logowaniu z nieprawidłowym hasłem")
|
||||
void shouldFailLoginWithIncorrectPassword() {
|
||||
logger.info("Test obsługi błędnych danych logowania - rozpoczęcie");
|
||||
String email = "user_" + UUID.randomUUID().toString().substring(0, 8) + "@example.com";
|
||||
String password = "password123";
|
||||
|
||||
ClientRegistrationDTO registrationDTO = new ClientRegistrationDTO();
|
||||
registrationDTO.setEmail(email);
|
||||
registrationDTO.setFirstName("Jan");
|
||||
registrationDTO.setLastName("Kowalski");
|
||||
registrationDTO.setPassword(password);
|
||||
restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/register"),
|
||||
registrationDTO,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
|
||||
AuthRequestDTO loginRequest = new AuthRequestDTO();
|
||||
loginRequest.setEmail(email);
|
||||
loginRequest.setPassword("wrongPassword");
|
||||
logger.debug("Przygotowano nieprawidłowe dane logowania");
|
||||
|
||||
ResponseEntity<AuthResponseDTO> response = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/login"),
|
||||
loginRequest,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
logger.info("Wykonano próbę logowania z błędnymi danymi");
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
logger.info("Test obsługi błędnych danych - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.customExceptions.ClientAlreadyExistsException;
|
||||
import _11.asktpk.artisanconnectbackend.customExceptions.WrongLoginPasswordException;
|
||||
import _11.asktpk.artisanconnectbackend.dto.AuthResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Role;
|
||||
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
||||
import _11.asktpk.artisanconnectbackend.service.AuthService;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class AuthServiceTest {
|
||||
|
||||
private final ClientService clientService = Mockito.mock(ClientService.class);
|
||||
private final PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
|
||||
private final JwtUtil jwtUtil = Mockito.mock(JwtUtil.class);
|
||||
private final AuthService authService = new AuthService(clientService, jwtUtil, passwordEncoder);
|
||||
|
||||
|
||||
@Test
|
||||
@DisplayName("Test logowania - poprawne dane")
|
||||
public void testLoginSuccess() throws Exception {
|
||||
String email = "test@example.com";
|
||||
String password = "password";
|
||||
Client client = new Client();
|
||||
client.setEmail(email);
|
||||
client.setPassword("encodedPassword");
|
||||
client.setRole(new Role());
|
||||
|
||||
when(clientService.getClientByEmail(email)).thenReturn(client);
|
||||
when(passwordEncoder.matches(password, client.getPassword())).thenReturn(true);
|
||||
when(jwtUtil.generateToken(email, client.getRole().getRole(), client.getId())).thenReturn("token");
|
||||
|
||||
AuthResponseDTO response = authService.login(email, password);
|
||||
|
||||
assertNotNull(response, "Odpowiedź nie powinna być null");
|
||||
assertEquals("token", response.getToken(), "Token w odpowiedzi powinien być poprawny");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test logowania - niepoprawne hasło")
|
||||
public void testLoginWrongPassword() {
|
||||
String email = "test@example.com";
|
||||
String password = "wrongPassword";
|
||||
Client client = new Client();
|
||||
client.setEmail(email);
|
||||
client.setPassword("encodedPassword");
|
||||
|
||||
when(clientService.getClientByEmail(email)).thenReturn(client);
|
||||
when(passwordEncoder.matches(password, client.getPassword())).thenReturn(false);
|
||||
|
||||
assertThrows(WrongLoginPasswordException.class, () -> authService.login(email, password),
|
||||
"Powinien zostać rzucony WrongLoginPasswordException");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test rejestracji - nowy użytkownik")
|
||||
public void testRegisterNewUser() throws Exception {
|
||||
String email = "new@example.com";
|
||||
String password = "password";
|
||||
String firstName = "Jan";
|
||||
String lastName = "Kowalski";
|
||||
|
||||
when(clientService.getClientByEmail(email)).thenReturn(null);
|
||||
when(passwordEncoder.encode(password)).thenReturn("encodedPassword");
|
||||
when(clientService.registerClient(any(Client.class))).thenReturn(new ClientDTO());
|
||||
|
||||
AuthResponseDTO response = authService.register(email, password, firstName, lastName);
|
||||
|
||||
assertNotNull(response, "Odpowiedź nie powinna być null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test rejestracji - użytkownik już istnieje")
|
||||
public void testRegisterExistingUser() {
|
||||
String email = "existing@example.com";
|
||||
String password = "password";
|
||||
String firstName = "Jan";
|
||||
String lastName = "Kowalski";
|
||||
|
||||
when(clientService.getClientByEmail(email)).thenReturn(new Client());
|
||||
|
||||
assertThrows(ClientAlreadyExistsException.class, () -> authService.register(email, password, firstName, lastName),
|
||||
"Powinien zostać rzucony ClientAlreadyExistsException");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test wylogowania z poprawnym tokenem")
|
||||
public void testLogoutWithValidToken() {
|
||||
String token = "valid.token.here";
|
||||
|
||||
when(jwtUtil.isBlacklisted(token)).thenReturn(false);
|
||||
|
||||
authService.logout(token);
|
||||
|
||||
verify(jwtUtil, times(1)).blacklistToken(token);
|
||||
|
||||
when(jwtUtil.isBlacklisted(token)).thenReturn(true);
|
||||
assertTrue(jwtUtil.isBlacklisted(token), "Token powinien być na czarnej liście po wylogowaniu");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test wylogowania bez tokena")
|
||||
public void testLogoutWithoutToken() {
|
||||
authService.logout(null);
|
||||
|
||||
verify(jwtUtil, never()).blacklistToken(anyString());
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.controller.ClientController;
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
class ClientControllerTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Mock
|
||||
private ClientService clientService;
|
||||
|
||||
@InjectMocks
|
||||
private ClientController clientController;
|
||||
|
||||
private ClientDTO sampleClientDTO;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Inicjalizacja konfiguracji testu...");
|
||||
MockitoAnnotations.openMocks(this);
|
||||
mockMvc = MockMvcBuilders.standaloneSetup(clientController).build();
|
||||
|
||||
sampleClientDTO = new ClientDTO();
|
||||
sampleClientDTO.setId(1L);
|
||||
sampleClientDTO.setEmail("test@example.com");
|
||||
sampleClientDTO.setFirstName("John");
|
||||
sampleClientDTO.setLastName("Doe");
|
||||
sampleClientDTO.setRole("USER");
|
||||
System.out.println("Konfiguracja testu zakończona z przykładowym klientem: " + sampleClientDTO);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić listę klientów")
|
||||
void getAllClients_ShouldReturnListOfClients() throws Exception {
|
||||
System.out.println("Uruchamianie testu: getAllClients_ShouldReturnListOfClients");
|
||||
|
||||
List<ClientDTO> clients = Collections.singletonList(sampleClientDTO);
|
||||
when(clientService.getAllClients()).thenReturn(clients);
|
||||
System.out.println("Konfiguracja mocka: clientService.getAllClients() zwróci " + clients);
|
||||
|
||||
mockMvc.perform(get("/api/v1/clients/get/all"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].id").value(1L))
|
||||
.andExpect(jsonPath("$[0].email").value("test@example.com"));
|
||||
|
||||
verify(clientService, times(1)).getAllClients();
|
||||
System.out.println("Test zaliczony: Pomyślnie pobrano listę klientów");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien utworzyć nowego klienta")
|
||||
void addClient_WhenClientNotExists_ShouldCreateClient() throws Exception {
|
||||
System.out.println("Uruchamianie testu: addClient_WhenClientNotExists_ShouldCreateClient");
|
||||
|
||||
when(clientService.clientExists(anyLong())).thenReturn(false);
|
||||
when(clientService.addClient(any(ClientDTO.class))).thenReturn(sampleClientDTO);
|
||||
System.out.println("Konfiguracja mocka: clientService.addClient() zwróci " + sampleClientDTO);
|
||||
|
||||
mockMvc.perform(post("/api/v1/clients/add")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(sampleClientDTO)))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(jsonPath("$.id").value(1L));
|
||||
|
||||
verify(clientService, times(1)).addClient(any(ClientDTO.class));
|
||||
System.out.println("Test zaliczony: Pomyślnie utworzono nowego klienta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić 409 gdy klient istnieje")
|
||||
void addClient_WhenClientExists_ShouldReturnConflict() throws Exception {
|
||||
System.out.println("Uruchamianie testu: addClient_WhenClientExists_ShouldReturnConflict");
|
||||
|
||||
when(clientService.clientExists(anyLong())).thenReturn(true);
|
||||
System.out.println("Konfiguracja mocka: clientService.clientExists() zwróci true");
|
||||
|
||||
mockMvc.perform(post("/api/v1/clients/add")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(sampleClientDTO)))
|
||||
.andExpect(status().isConflict());
|
||||
|
||||
verify(clientService, times(0)).addClient(any(ClientDTO.class));
|
||||
System.out.println("Test zaliczony: Poprawnie zwrócono 409 dla istniejącego klienta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zaktualizować istniejącego klienta")
|
||||
void updateClient_WhenClientExists_ShouldUpdateClient() throws Exception {
|
||||
System.out.println("Uruchamianie testu: updateClient_WhenClientExists_ShouldUpdateClient");
|
||||
|
||||
when(clientService.clientExists(1L)).thenReturn(true);
|
||||
when(clientService.updateClient(anyLong(), any(ClientDTO.class))).thenReturn(sampleClientDTO);
|
||||
System.out.println("Konfiguracja mocka: clientService.updateClient() zwróci " + sampleClientDTO);
|
||||
|
||||
mockMvc.perform(put("/api/v1/clients/edit/1")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(sampleClientDTO)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(1L));
|
||||
|
||||
verify(clientService, times(1)).updateClient(anyLong(), any(ClientDTO.class));
|
||||
System.out.println("Test zaliczony: Pomyślnie zaktualizowano klienta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić 404 gdy klient nie istnieje")
|
||||
void updateClient_WhenClientNotExists_ShouldReturnNotFound() throws Exception {
|
||||
System.out.println("Uruchamianie testu: updateClient_WhenClientNotExists_ShouldReturnNotFound");
|
||||
|
||||
when(clientService.clientExists(1L)).thenReturn(false);
|
||||
System.out.println("Konfiguracja mocka: clientService.clientExists(1L) zwróci false");
|
||||
|
||||
mockMvc.perform(put("/api/v1/clients/edit/1")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(sampleClientDTO)))
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
verify(clientService, times(0)).updateClient(anyLong(), any(ClientDTO.class));
|
||||
System.out.println("Test zaliczony: Poprawnie zwrócono 404 dla nieistniejącego klienta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien usunąć istniejącego klienta")
|
||||
void deleteClient_WhenClientExists_ShouldDeleteClient() throws Exception {
|
||||
System.out.println("Uruchamianie testu: deleteClient_WhenClientExists_ShouldDeleteClient");
|
||||
|
||||
when(clientService.clientExists(1L)).thenReturn(true);
|
||||
doNothing().when(clientService).deleteClient(1L);
|
||||
System.out.println("Konfiguracja mocka: clientService.deleteClient(1L) nie zrobi nic");
|
||||
|
||||
mockMvc.perform(delete("/api/v1/clients/delete/1"))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
verify(clientService, times(1)).deleteClient(1L);
|
||||
System.out.println("Test zaliczony: Pomyślnie usunięto klienta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić 404 gdy klient nie istnieje")
|
||||
void deleteClient_WhenClientNotExists_ShouldReturnNotFound() throws Exception {
|
||||
System.out.println("Uruchamianie testu: deleteClient_WhenClientNotExists_ShouldReturnNotFound");
|
||||
|
||||
when(clientService.clientExists(1L)).thenReturn(false);
|
||||
System.out.println("Konfiguracja mocka: clientService.clientExists(1L) zwróci false");
|
||||
|
||||
mockMvc.perform(delete("/api/v1/clients/delete/1"))
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
verify(clientService, times(0)).deleteClient(anyLong());
|
||||
System.out.println("Test zaliczony: Poprawnie zwrócono 404 dla nieistniejącego klienta");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Role;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.RolesRepository;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class ClientServiceTest {
|
||||
|
||||
private final ClientRepository clientRepository = Mockito.mock(ClientRepository.class);
|
||||
private final RolesRepository rolesRepository = Mockito.mock(RolesRepository.class);
|
||||
|
||||
private final ClientService clientService = new ClientService(clientRepository, rolesRepository);
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania wszystkich klientów")
|
||||
public void testGetAllClients() {
|
||||
System.out.println("Rozpoczęcie testu: testGetAllClients - Test pobierania wszystkich klientów");
|
||||
|
||||
Client client1 = new Client();
|
||||
client1.setId(1L);
|
||||
client1.setEmail("client1@example.com");
|
||||
client1.setRole(new Role());
|
||||
|
||||
Client client2 = new Client();
|
||||
client2.setId(2L);
|
||||
client2.setEmail("client2@example.com");
|
||||
client2.setRole(new Role());
|
||||
|
||||
when(clientRepository.findAll()).thenReturn(List.of(client1, client2));
|
||||
|
||||
List<ClientDTO> clients = clientService.getAllClients();
|
||||
|
||||
System.out.println("Pobrano listę klientów, liczba elementów: " + clients.size());
|
||||
assertEquals(2, clients.size(), "Lista klientów powinna zawierać 2 elementy");
|
||||
System.out.println("Pierwszy klient na liście: " + clients.getFirst().getEmail());
|
||||
assertEquals("client1@example.com", clients.getFirst().getEmail(), "Email pierwszego klienta powinien być poprawny");
|
||||
|
||||
System.out.println("Test pobierania wszystkich klientów zakończony sukcesem. Zwrócono " + clients.size() + " klientów.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania klienta po ID - klient istnieje")
|
||||
public void testGetClientByIdExists() {
|
||||
Long clientId = 1L;
|
||||
System.out.println("Rozpoczęcie testu: testGetClientByIdExists - Test pobierania klienta po ID (ID: " + clientId + ")");
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(clientId);
|
||||
client.setEmail("client@example.com");
|
||||
client.setRole(new Role());
|
||||
|
||||
when(clientRepository.findById(clientId)).thenReturn(Optional.of(client));
|
||||
|
||||
Client retrievedClient = clientService.getClientById(clientId);
|
||||
|
||||
System.out.println("Pobrano klienta o ID: " + (retrievedClient != null ? retrievedClient.getId() : "null"));
|
||||
assertNotNull(retrievedClient, "Pobrany klient nie powinien być null");
|
||||
assertEquals(clientId, retrievedClient.getId(), "ID klienta powinno być zgodne");
|
||||
|
||||
System.out.println("Test pobierania klienta po ID (ID: " + clientId + ") zakończony sukcesem. Znaleziono klienta: " + retrievedClient.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania klienta po ID - klient nie istnieje")
|
||||
public void testGetClientByIdNotExists() {
|
||||
Long clientId = 1L;
|
||||
System.out.println("Rozpoczęcie testu: testGetClientByIdNotExists - Test pobierania nieistniejącego klienta (ID: " + clientId + ")");
|
||||
|
||||
when(clientRepository.findById(clientId)).thenReturn(Optional.empty());
|
||||
|
||||
Client retrievedClient = clientService.getClientById(clientId);
|
||||
|
||||
System.out.println("Próba pobrania nieistniejącego klienta zwróciła: " + retrievedClient);
|
||||
assertNull(retrievedClient, "Pobrany klient powinien być null, gdy nie istnieje");
|
||||
|
||||
System.out.println("Test pobierania nieistniejącego klienta (ID: " + clientId + ") zakończony sukcesem. Zwrócono null zgodnie z oczekiwaniami.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania klienta po emailu")
|
||||
public void testGetClientByEmail() {
|
||||
String email = "client@example.com";
|
||||
System.out.println("Rozpoczęcie testu: testGetClientByEmail - Test pobierania klienta po emailu (" + email + ")");
|
||||
|
||||
Client client = new Client();
|
||||
client.setEmail(email);
|
||||
|
||||
when(clientRepository.findByEmail(email)).thenReturn(client);
|
||||
|
||||
Client retrievedClient = clientService.getClientByEmail(email);
|
||||
|
||||
System.out.println("Pobrano klienta o emailu: " + (retrievedClient != null ? retrievedClient.getEmail() : "null"));
|
||||
assertNotNull(retrievedClient, "Pobrany klient nie powinien być null");
|
||||
assertEquals(email, retrievedClient.getEmail(), "Email klienta powinien być zgodny");
|
||||
|
||||
System.out.println("Test pobierania klienta po emailu (" + email + ") zakończony sukcesem.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test dodawania klienta")
|
||||
public void testAddClient() {
|
||||
System.out.println("Rozpoczęcie testu: testAddClient - Test dodawania nowego klienta");
|
||||
|
||||
ClientDTO clientDTO = new ClientDTO();
|
||||
clientDTO.setEmail("newclient@example.com");
|
||||
clientDTO.setRole("USER");
|
||||
|
||||
Client client = new Client();
|
||||
client.setEmail("newclient@example.com");
|
||||
client.setRole(new Role());
|
||||
|
||||
when(clientRepository.save(any(Client.class))).thenReturn(client);
|
||||
|
||||
ClientDTO addedClient = clientService.addClient(clientDTO);
|
||||
|
||||
System.out.println("Dodano nowego klienta: " + (addedClient != null ? addedClient.getEmail() : "null"));
|
||||
assertNotNull(addedClient, "Dodany klient nie powinien być null");
|
||||
assertEquals("newclient@example.com", addedClient.getEmail(), "Email dodanego klienta powinien być poprawny");
|
||||
|
||||
System.out.println("Test dodawania klienta zakończony sukcesem. Dodano klienta: " + addedClient.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test aktualizacji klienta")
|
||||
public void testUpdateClient() {
|
||||
Long clientId = 1L;
|
||||
System.out.println("Rozpoczęcie testu: testUpdateClient - Test aktualizacji klienta (ID: " + clientId + ")");
|
||||
|
||||
Client existingClient = new Client();
|
||||
existingClient.setId(clientId);
|
||||
existingClient.setEmail("old@example.com");
|
||||
|
||||
ClientDTO updatedDTO = new ClientDTO();
|
||||
updatedDTO.setEmail("updated@example.com");
|
||||
updatedDTO.setRole("USER");
|
||||
|
||||
Role role = new Role();
|
||||
role.setRole("USER");
|
||||
|
||||
when(clientRepository.findById(clientId)).thenReturn(Optional.of(existingClient));
|
||||
when(rolesRepository.findRoleByRole("USER")).thenReturn(role);
|
||||
when(clientRepository.save(any(Client.class))).thenReturn(existingClient);
|
||||
|
||||
ClientDTO updatedClient = clientService.updateClient(clientId, updatedDTO);
|
||||
|
||||
System.out.println("Zaktualizowano klienta. Nowy email: " + updatedClient.getEmail());
|
||||
assertEquals("updated@example.com", updatedClient.getEmail(), "Email klienta powinien być zaktualizowany");
|
||||
|
||||
System.out.println("Test aktualizacji klienta (ID: " + clientId + ") zakończony sukcesem. Nowy email: " + updatedClient.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test aktualizacji klienta - klient nie istnieje")
|
||||
public void testUpdateClientNotExists() {
|
||||
long clientId = 1L;
|
||||
System.out.println("Rozpoczęcie testu: testUpdateClientNotExists - Test aktualizacji nieistniejącego klienta (ID: " + clientId + ")");
|
||||
|
||||
ClientDTO updatedDTO = new ClientDTO();
|
||||
updatedDTO.setEmail("updated@example.com");
|
||||
|
||||
when(clientRepository.findById(clientId)).thenReturn(Optional.empty());
|
||||
|
||||
System.out.println("Oczekiwanie na EntityNotFoundException...");
|
||||
assertThrows(EntityNotFoundException.class, () -> clientService.updateClient(clientId, updatedDTO),
|
||||
"Powinien zostać rzucony EntityNotFoundException");
|
||||
|
||||
System.out.println("Test aktualizacji nieistniejącego klienta (ID: " + clientId + ") zakończony sukcesem. Rzucono wyjątek EntityNotFoundException zgodnie z oczekiwaniami.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test usuwania klienta")
|
||||
public void testDeleteClient() {
|
||||
Long clientId = 1L;
|
||||
System.out.println("Rozpoczęcie testu: testDeleteClient - Test usuwania klienta (ID: " + clientId + ")");
|
||||
|
||||
clientService.deleteClient(clientId);
|
||||
|
||||
verify(clientRepository, times(1)).deleteById(clientId);
|
||||
System.out.println("Weryfikacja: metoda deleteById została wywołana 1 raz z ID: " + clientId);
|
||||
|
||||
System.out.println("Test usuwania klienta (ID: " + clientId + ") zakończony sukcesem.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test konwersji encji do DTO")
|
||||
public void testToDto() {
|
||||
System.out.println("Rozpoczęcie testu: testToDto - Test konwersji encji Client do ClientDTO");
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(1L);
|
||||
client.setEmail("client@example.com");
|
||||
client.setFirstName("Jan");
|
||||
client.setLastName("Kowalski");
|
||||
client.setImage("image.jpg");
|
||||
Role role = new Role();
|
||||
role.setRole("USER");
|
||||
client.setRole(role);
|
||||
|
||||
System.out.println("Przygotowano encję Client do konwersji:");
|
||||
System.out.println("ID: " + client.getId());
|
||||
System.out.println("Email: " + client.getEmail());
|
||||
System.out.println("Imię: " + client.getFirstName());
|
||||
System.out.println("Nazwisko: " + client.getLastName());
|
||||
System.out.println("Obraz: " + client.getImage());
|
||||
System.out.println("Rola: " + client.getRole().getRole());
|
||||
|
||||
ClientDTO dto = clientService.toDto(client);
|
||||
|
||||
System.out.println("Wynik konwersji do DTO:");
|
||||
System.out.println("ID: " + dto.getId());
|
||||
System.out.println("Email: " + dto.getEmail());
|
||||
System.out.println("Imię: " + dto.getFirstName());
|
||||
System.out.println("Nazwisko: " + dto.getLastName());
|
||||
System.out.println("Obraz: " + dto.getImage());
|
||||
System.out.println("Rola: " + dto.getRole());
|
||||
|
||||
assertEquals(1L, dto.getId(), "ID w DTO powinno być zgodne");
|
||||
assertEquals("client@example.com", dto.getEmail(), "Email w DTO powinien być zgodny");
|
||||
assertEquals("Jan", dto.getFirstName(), "Imię w DTO powinno być zgodne");
|
||||
assertEquals("Kowalski", dto.getLastName(), "Nazwisko w DTO powinno być zgodne");
|
||||
assertEquals("image.jpg", dto.getImage(), "Obraz w DTO powinien być zgodny");
|
||||
assertEquals("USER", dto.getRole(), "Rola w DTO powinna być zgodna");
|
||||
|
||||
System.out.println("Test konwersji encji do DTO zakończony sukcesem. Wszystkie pola zostały poprawnie zmapowane.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
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.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class EmailControllerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private JwtUtil jwtUtil;
|
||||
|
||||
@Test
|
||||
@DisplayName("Wysyłanie Maila z waznym tokenem")
|
||||
void testSendEmailWithValidAuthToken() throws Exception {
|
||||
System.out.println("Startowanie testSendEmailWithValidAuthToken");
|
||||
String jsonPayload = """
|
||||
{
|
||||
"to": "test@example.com",
|
||||
"subject": "Test Subject",
|
||||
"body": "Test Body"
|
||||
}
|
||||
""";
|
||||
System.out.println("Wysyłanie JSON payload: " + jsonPayload);
|
||||
|
||||
String jwtToken = "Bearer " + jwtUtil.generateToken("test@example.com", "USER", 1L);
|
||||
|
||||
MvcResult result = mockMvc.perform(post("/api/v1/email/send")
|
||||
.header("Authorization", jwtToken)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(jsonPayload))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("Email wysłany pomyślnie"))
|
||||
.andReturn();
|
||||
|
||||
System.out.println("Status odpowiedzi: " + result.getResponse().getStatus());
|
||||
System.out.println("Treść odpowiedzi: " + result.getResponse().getContentAsString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Wysyłanie Maila bez tokena")
|
||||
void testSendEmailWithoutAuthToken() throws Exception {
|
||||
System.out.println("Startowanie testSendEmailWithoutAuthToken");
|
||||
String jsonPayload = """
|
||||
{
|
||||
"to": "test@example.com",
|
||||
"subject": "Test Subject",
|
||||
"body": "Test Body"
|
||||
}
|
||||
""";
|
||||
System.out.println("Wysyłanie JSON payload: " + jsonPayload);
|
||||
|
||||
MvcResult result = mockMvc.perform(post("/api/v1/email/send")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(jsonPayload))
|
||||
.andExpect(status().isForbidden())
|
||||
.andReturn();
|
||||
|
||||
System.out.println("Status odpowiedzi: " + result.getResponse().getStatus());
|
||||
System.out.println("Treść odpowiedzi: " + result.getResponse().getContentAsString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.controller.NoticeController;
|
||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Tools;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class NoticeControllerTest {
|
||||
|
||||
@Mock
|
||||
private NoticeService noticeService;
|
||||
|
||||
@Mock
|
||||
private ClientService clientService;
|
||||
|
||||
@Mock
|
||||
private Tools tools;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@InjectMocks
|
||||
private NoticeController noticeController;
|
||||
|
||||
private NoticeResponseDTO sampleNotice;
|
||||
private NoticeRequestDTO sampleNoticeRequest;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Inicjalizacja danych testowych...");
|
||||
|
||||
sampleNotice = new NoticeResponseDTO();
|
||||
sampleNotice.setNoticeId(1L);
|
||||
sampleNotice.setTitle("Testowe ogłoszenie");
|
||||
sampleNotice.setClientId(1L);
|
||||
sampleNotice.setDescription("Opis testowego ogłoszenia");
|
||||
sampleNotice.setPrice(100.0);
|
||||
sampleNotice.setCategory(Enums.Category.Woodworking);
|
||||
sampleNotice.setStatus(Enums.Status.ACTIVE);
|
||||
sampleNotice.setPublishDate(LocalDateTime.now());
|
||||
|
||||
sampleNoticeRequest = new NoticeRequestDTO();
|
||||
sampleNoticeRequest.setTitle("Testowe ogłoszenie");
|
||||
sampleNoticeRequest.setClientId(1L);
|
||||
sampleNoticeRequest.setDescription("Opis testowego ogłoszenia");
|
||||
sampleNoticeRequest.setPrice(100.0);
|
||||
sampleNoticeRequest.setCategory(Enums.Category.Woodworking);
|
||||
sampleNoticeRequest.setStatus(Enums.Status.ACTIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie wszystkich ogłoszeń")
|
||||
void getAllNotices_ShouldReturnListOfNotices() {
|
||||
when(noticeService.getAllNotices()).thenReturn(List.of(sampleNotice));
|
||||
|
||||
List<NoticeResponseDTO> result = noticeController.getAllNotices();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
System.out.println("Test GET /notices zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie istniejącego ogłoszenia")
|
||||
void getNoticeById_WhenNoticeExists_ShouldReturnNotice() {
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.getNoticeById(1L)).thenReturn(sampleNotice);
|
||||
|
||||
ResponseEntity<?> response = noticeController.getNoticeById(1L);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
System.out.println("Test GET /notices/{id} (istniejące) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie nieistniejącego ogłoszenia")
|
||||
void getNoticeById_WhenNoticeNotExists_ShouldReturnNotFound() {
|
||||
when(noticeService.noticeExists(1L)).thenReturn(false);
|
||||
|
||||
ResponseEntity<?> response = noticeController.getNoticeById(1L);
|
||||
|
||||
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
|
||||
System.out.println("Test GET /notices/{id} (nieistniejące) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie poprawnego ogłoszenia")
|
||||
void addNotice_WithValidData_ShouldCreateNotice() {
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(clientService.clientExists(1L)).thenReturn(true);
|
||||
when(noticeService.addNotice(any(NoticeRequestDTO.class))).thenReturn(1L);
|
||||
|
||||
ResponseEntity<NoticeAdditionDTO> response = noticeController.addNotice(sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.CREATED, response.getStatusCode());
|
||||
System.out.println("Test POST /notices (poprawne dane) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie ogłoszenia z błędną kategorią")
|
||||
void addNotice_WithInvalidCategory_ShouldReturnBadRequest() {
|
||||
sampleNoticeRequest.setCategory(null);
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(clientService.clientExists(1L)).thenReturn(true);
|
||||
|
||||
ResponseEntity<NoticeAdditionDTO> response = noticeController.addNotice(sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
|
||||
System.out.println("Test POST /notices (błędna kategoria) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie ogłoszenia przez nieistniejącego klienta")
|
||||
void addNotice_WhenClientNotExists_ShouldReturnBadRequest() {
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(clientService.clientExists(1L)).thenReturn(false);
|
||||
|
||||
ResponseEntity<NoticeAdditionDTO> response = noticeController.addNotice(sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
|
||||
System.out.println("Test POST /notices (nieistniejący klient) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Aktualizacja własnego ogłoszenia")
|
||||
void editNotice_WhenNoticeExistsAndOwnedByClient_ShouldUpdateNotice() {
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.isNoticeOwnedByClient(1L, 1L)).thenReturn(true);
|
||||
when(noticeService.updateNotice(anyLong(), any(NoticeRequestDTO.class))).thenReturn(sampleNotice);
|
||||
|
||||
ResponseEntity<Object> response = noticeController.editNotice(1L, sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
System.out.println("Test PUT /notices/{id} (własne ogłoszenie) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Próba aktualizacji cudzego ogłoszenia")
|
||||
void editNotice_WhenNoticeNotOwnedByClient_ShouldReturnForbidden() {
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(2L);
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.isNoticeOwnedByClient(1L, 2L)).thenReturn(false);
|
||||
|
||||
ResponseEntity<Object> response = noticeController.editNotice(1L, sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
|
||||
System.out.println("Test PUT /notices/{id} (cudze ogłoszenie) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Usunięcie własnego ogłoszenia")
|
||||
void deleteNotice_WhenNoticeExistsAndOwnedByClient_ShouldDeleteNotice() {
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.isNoticeOwnedByClient(1L, 1L)).thenReturn(true);
|
||||
|
||||
ResponseEntity<RequestResponseDTO> response = noticeController.deleteNotice(1L, request);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
verify(noticeService, times(1)).deleteNotice(1L);
|
||||
System.out.println("Test DELETE /notices/{id} (własne ogłoszenie) zakończony sukcesem");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.AttributeDto;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeRequestDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.*;
|
||||
import _11.asktpk.artisanconnectbackend.repository.*;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class NoticeServiceTest {
|
||||
|
||||
@Mock
|
||||
private NoticeRepository noticeRepository;
|
||||
|
||||
@Mock
|
||||
private ClientRepository clientRepository;
|
||||
|
||||
@Mock
|
||||
private AttributesRepository attributesRepository;
|
||||
|
||||
@Mock
|
||||
private AttributeValuesRepository attributeValuesRepository;
|
||||
|
||||
@InjectMocks
|
||||
private NoticeService noticeService;
|
||||
|
||||
private Notice sampleNotice;
|
||||
private NoticeRequestDTO sampleNoticeRequest;
|
||||
private Client sampleClient;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Przygotowanie danych testowych...");
|
||||
|
||||
sampleClient = new Client();
|
||||
sampleClient.setId(1L);
|
||||
sampleClient.setEmail("test@example.com");
|
||||
|
||||
sampleNotice = new Notice();
|
||||
sampleNotice.setIdNotice(1L);
|
||||
sampleNotice.setTitle("Testowe ogłoszenie");
|
||||
sampleNotice.setClient(sampleClient);
|
||||
sampleNotice.setDescription("Opis testowego ogłoszenia");
|
||||
sampleNotice.setPrice(100.0);
|
||||
sampleNotice.setCategory(Enums.Category.Woodworking);
|
||||
sampleNotice.setStatus(Enums.Status.ACTIVE);
|
||||
sampleNotice.setPublishDate(LocalDateTime.now());
|
||||
|
||||
sampleNoticeRequest = new NoticeRequestDTO();
|
||||
sampleNoticeRequest.setTitle("Testowe ogłoszenie");
|
||||
sampleNoticeRequest.setClientId(1L);
|
||||
sampleNoticeRequest.setDescription("Opis testowego ogłoszenia");
|
||||
sampleNoticeRequest.setPrice(100.0);
|
||||
sampleNoticeRequest.setCategory(Enums.Category.Woodworking);
|
||||
sampleNoticeRequest.setStatus(Enums.Status.ACTIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie wszystkich ogłoszeń - powinno zwrócić listę ogłoszeń")
|
||||
void getAllNotices_ShouldReturnListOfNotices() {
|
||||
when(noticeRepository.findAll()).thenReturn(List.of(sampleNotice));
|
||||
|
||||
List<NoticeResponseDTO> result = noticeService.getAllNotices();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
System.out.println("Test pobrania wszystkich ogłoszeń zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie ogłoszenia po ID - gdy istnieje")
|
||||
void getNoticeById_WhenNoticeExists_ShouldReturnNotice() {
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.of(sampleNotice));
|
||||
|
||||
NoticeResponseDTO result = noticeService.getNoticeById(1L);
|
||||
|
||||
assertNotNull(result);
|
||||
System.out.println("Test pobrania istniejącego ogłoszenia zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie ogłoszenia po ID - gdy nie istnieje")
|
||||
void getNoticeById_WhenNoticeNotExists_ShouldThrowException() {
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(EntityNotFoundException.class, () -> noticeService.getNoticeById(1L));
|
||||
System.out.println("Test pobrania nieistniejącego ogłoszenia zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie nowego ogłoszenia - poprawne dane")
|
||||
void addNotice_WithValidData_ShouldCreateNotice() {
|
||||
when(clientRepository.findById(1L)).thenReturn(Optional.of(sampleClient));
|
||||
when(noticeRepository.save(any(Notice.class))).thenReturn(sampleNotice);
|
||||
|
||||
Long result = noticeService.addNotice(sampleNoticeRequest);
|
||||
|
||||
assertNotNull(result);
|
||||
System.out.println("Test dodania ogłoszenia zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie ogłoszenia z atrybutami")
|
||||
void addNotice_WithAttributes_ShouldSaveAttributes() {
|
||||
AttributeDto attributeDto = new AttributeDto();
|
||||
attributeDto.setName("Materiał");
|
||||
attributeDto.setValue("Drewno");
|
||||
sampleNoticeRequest.setAttributes(List.of(attributeDto));
|
||||
|
||||
when(clientRepository.findById(1L)).thenReturn(Optional.of(sampleClient));
|
||||
when(noticeRepository.save(any(Notice.class))).thenReturn(sampleNotice);
|
||||
when(attributesRepository.findByName(anyString())).thenReturn(Optional.empty());
|
||||
when(attributeValuesRepository.findByAttributeAndValue(any(), anyString())).thenReturn(Optional.empty());
|
||||
|
||||
Long result = noticeService.addNotice(sampleNoticeRequest);
|
||||
|
||||
assertNotNull(result);
|
||||
System.out.println("Test dodania ogłoszenia z atrybutami zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Usunięcie istniejącego ogłoszenia")
|
||||
void deleteNotice_WhenNoticeExists_ShouldDeleteNotice() {
|
||||
when(noticeRepository.existsById(1L)).thenReturn(true);
|
||||
|
||||
noticeService.deleteNotice(1L);
|
||||
|
||||
System.out.println("Test usunięcia ogłoszenia zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Sprawdzenie właściciela ogłoszenia - gdy należy do klienta")
|
||||
void isNoticeOwnedByClient_WhenOwned_ShouldReturnTrue() {
|
||||
when(noticeRepository.existsByIdNoticeAndClientId(1L, 1L)).thenReturn(true);
|
||||
|
||||
boolean result = noticeService.isNoticeOwnedByClient(1L, 1L);
|
||||
|
||||
assertTrue(result);
|
||||
System.out.println("Test sprawdzenia właściciela (true) zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Boostowanie ogłoszenia - aktualizacja daty publikacji")
|
||||
void boostNotice_ShouldUpdatePublishDate() {
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.of(sampleNotice));
|
||||
when(noticeRepository.save(any(Notice.class))).thenReturn(sampleNotice);
|
||||
|
||||
noticeService.boostNotice(1L);
|
||||
|
||||
assertNotNull(sampleNotice.getPublishDate());
|
||||
System.out.println("Test boostowania ogłoszenia zakończony");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.controller.OrderController;
|
||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Order;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Payment;
|
||||
import _11.asktpk.artisanconnectbackend.service.OrderService;
|
||||
import _11.asktpk.artisanconnectbackend.service.PaymentService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Tools;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class OrderControllerTest {
|
||||
|
||||
private final OrderService orderService = Mockito.mock(OrderService.class);
|
||||
private final PaymentService paymentService = Mockito.mock(PaymentService.class);
|
||||
private final Tools tools = Mockito.mock(Tools.class);
|
||||
private final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
|
||||
|
||||
private OrderController orderController;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
orderController = new OrderController(orderService, paymentService, tools);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test dodawania zamówienia")
|
||||
public void testAddOrder() {
|
||||
OrderDTO orderDTO = new OrderDTO();
|
||||
orderDTO.setClientId(1L);
|
||||
orderDTO.setNoticeId(1L);
|
||||
orderDTO.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(orderService.addOrder(orderDTO)).thenReturn(1L);
|
||||
|
||||
ResponseEntity<?> response = orderController.addClient(orderDTO, request);
|
||||
|
||||
assertEquals(HttpStatus.CREATED, response.getStatusCode(), "Status odpowiedzi powinien być 201 CREATED");
|
||||
assertEquals(1L, response.getBody(), "Ciało odpowiedzi powinno zawierać ID zamówienia");
|
||||
|
||||
System.out.println("Test dodawania zamówienia przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test zmiany statusu zamówienia")
|
||||
public void testChangeStatus() {
|
||||
OrderStatusDTO orderStatusDTO = new OrderStatusDTO();
|
||||
orderStatusDTO.setId(1L);
|
||||
orderStatusDTO.setStatus(Enums.OrderStatus.COMPLETED);
|
||||
|
||||
when(orderService.changeOrderStatus(1L, Enums.OrderStatus.COMPLETED)).thenReturn(1L);
|
||||
|
||||
ResponseEntity<?> response = orderController.changeStatus(orderStatusDTO);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status odpowiedzi powinien być 200 OK");
|
||||
assertEquals(1L, response.getBody(), "Ciało odpowiedzi powinno zawierać ID zamówienia");
|
||||
|
||||
System.out.println("Test zmiany statusu zamówienia przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania tokena płatności")
|
||||
public void testFetchToken() {
|
||||
Long orderId = 1L;
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
order.setAmount(10.00);
|
||||
order.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(1L);
|
||||
client.setEmail("test@example.com");
|
||||
client.setFirstName("Jan");
|
||||
client.setLastName("Kowalski");
|
||||
|
||||
Notice notice = new Notice();
|
||||
notice.setTitle("Test Notice");
|
||||
|
||||
order.setClient(client);
|
||||
order.setNotice(notice);
|
||||
|
||||
OAuthPaymentResponseDTO oAuthResponse = new OAuthPaymentResponseDTO();
|
||||
oAuthResponse.setAccess_token("testAccessToken");
|
||||
|
||||
when(orderService.getOrderById(orderId)).thenReturn(order);
|
||||
when(paymentService.getOAuthToken()).thenReturn(oAuthResponse);
|
||||
when(paymentService.createTransaction(eq(order), eq("testAccessToken"), any(TransactionPaymentRequestDTO.class)))
|
||||
.thenReturn("http://payment.url");
|
||||
|
||||
ResponseEntity<?> response = orderController.fetchToken(orderId);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status odpowiedzi powinien być 200 OK");
|
||||
assertEquals("http://payment.url", response.getBody(), "Ciało odpowiedzi powinno zawierać URL płatności");
|
||||
|
||||
System.out.println("Test pobierania tokena płatności przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania wszystkich zamówień")
|
||||
public void testGetAllOrders() {
|
||||
Long clientId = 1L;
|
||||
Order order1 = new Order();
|
||||
order1.setId(1L);
|
||||
order1.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
order1.setStatus(Enums.OrderStatus.PENDING);
|
||||
order1.setAmount(10.00);
|
||||
order1.setCreatedAt(LocalDateTime.now());
|
||||
|
||||
Order order2 = new Order();
|
||||
order2.setId(2L);
|
||||
order2.setOrderType(Enums.OrderType.BOOST);
|
||||
order2.setStatus(Enums.OrderStatus.COMPLETED);
|
||||
order2.setAmount(8.00);
|
||||
order2.setCreatedAt(LocalDateTime.now());
|
||||
|
||||
List<Order> orders = List.of(order1, order2);
|
||||
|
||||
Payment payment1 = new Payment();
|
||||
payment1.setIdPayment(1L);
|
||||
payment1.setAmount(10.00);
|
||||
payment1.setStatus(Enums.PaymentStatus.PENDING);
|
||||
payment1.setTransactionPaymentUrl("http://payment.url/1");
|
||||
payment1.setTransactionId("trans1");
|
||||
|
||||
Payment payment2 = new Payment();
|
||||
payment2.setIdPayment(2L);
|
||||
payment2.setAmount(8.00);
|
||||
payment2.setStatus(Enums.PaymentStatus.CORRECT);
|
||||
payment2.setTransactionPaymentUrl("http://payment.url/2");
|
||||
payment2.setTransactionId("trans2");
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(clientId);
|
||||
when(orderService.getOrdersByClientId(clientId)).thenReturn(orders);
|
||||
when(paymentService.getPaymentsByOrderId(1L)).thenReturn(List.of(payment1));
|
||||
when(paymentService.getPaymentsByOrderId(2L)).thenReturn(List.of(payment2));
|
||||
|
||||
ResponseEntity<List<OrderWithPaymentsDTO>> response = orderController.getOrders(request);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status odpowiedzi powinien być 200 OK");
|
||||
List<OrderWithPaymentsDTO> dtoList = response.getBody();
|
||||
assertNotNull(dtoList, "Lista DTO nie powinna być null");
|
||||
assertEquals(2, dtoList.size(), "Lista DTO powinna zawierać 2 elementy");
|
||||
|
||||
OrderWithPaymentsDTO dto1 = dtoList.getFirst();
|
||||
assertEquals(1L, dto1.getOrderId(), "ID zamówienia w DTO powinno być 1");
|
||||
assertEquals("ACTIVATION", dto1.getOrderType(), "Typ zamówienia w DTO powinien być ACTIVATION");
|
||||
assertEquals("PENDING", dto1.getStatus(), "Status zamówienia w DTO powinien być PENDING");
|
||||
assertEquals(10.00, dto1.getAmount(), "Kwota zamówienia w DTO powinna być 10.00");
|
||||
assertEquals(1, dto1.getPayments().size(), "Liczba płatności w DTO powinna być 1");
|
||||
|
||||
System.out.println("Test pobierania wszystkich zamówień przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania zamówienia po ID")
|
||||
public void testGetOrderById() {
|
||||
Long clientId = 1L;
|
||||
Long orderId = 1L;
|
||||
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
order.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
order.setStatus(Enums.OrderStatus.PENDING);
|
||||
order.setAmount(10.00);
|
||||
order.setCreatedAt(LocalDateTime.now());
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(clientId);
|
||||
order.setClient(client);
|
||||
|
||||
Payment payment = new Payment();
|
||||
payment.setIdPayment(1L);
|
||||
payment.setAmount(10.00);
|
||||
payment.setStatus(Enums.PaymentStatus.PENDING);
|
||||
payment.setTransactionPaymentUrl("http://payment.url/1");
|
||||
payment.setTransactionId("trans1");
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(clientId);
|
||||
when(orderService.getOrderById(orderId)).thenReturn(order);
|
||||
when(paymentService.getPaymentsByOrderId(orderId)).thenReturn(List.of(payment));
|
||||
|
||||
ResponseEntity<OrderWithPaymentsDTO> response = orderController.getOrderById(request, orderId);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status odpowiedzi powinien być 200 OK");
|
||||
OrderWithPaymentsDTO dto = response.getBody();
|
||||
assertNotNull(dto, "DTO nie powinno być null");
|
||||
assertEquals(orderId, dto.getOrderId(), "ID zamówienia w DTO powinno być równe podanemu");
|
||||
|
||||
System.out.println("Test pobierania zamówienia po ID przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania zamówienia po ID - brak uprawnień")
|
||||
public void testGetOrderByIdForbidden() {
|
||||
Long clientId = 1L;
|
||||
Long orderId = 1L;
|
||||
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
order.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
order.setStatus(Enums.OrderStatus.PENDING);
|
||||
order.setAmount(10.00);
|
||||
order.setCreatedAt(LocalDateTime.now());
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(2L);
|
||||
order.setClient(client);
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(clientId);
|
||||
when(orderService.getOrderById(orderId)).thenReturn(order);
|
||||
|
||||
ResponseEntity<OrderWithPaymentsDTO> response = orderController.getOrderById(request, orderId);
|
||||
|
||||
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode(), "Status odpowiedzi powinien być 403 FORBIDDEN");
|
||||
|
||||
System.out.println("Test pobierania zamówienia po ID - brak uprawnień przeszedł pomyślnie.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.OrderDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Order;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.NoticeRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.OrderRepository;
|
||||
import _11.asktpk.artisanconnectbackend.service.OrderService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class OrderServiceTest {
|
||||
|
||||
private final OrderRepository orderRepository = Mockito.mock(OrderRepository.class);
|
||||
private final ClientRepository clientRepository = Mockito.mock(ClientRepository.class);
|
||||
private final NoticeRepository noticeRepository = Mockito.mock(NoticeRepository.class);
|
||||
private final OrderService orderService = new OrderService(orderRepository, clientRepository, noticeRepository);
|
||||
|
||||
@Test
|
||||
@DisplayName("Test dodawania zamówienia")
|
||||
public void testAddOrder() {
|
||||
OrderDTO orderDTO = new OrderDTO();
|
||||
orderDTO.setClientId(1L);
|
||||
orderDTO.setNoticeId(1L);
|
||||
orderDTO.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(1L);
|
||||
|
||||
Notice notice = new Notice();
|
||||
notice.setIdNotice(1L);
|
||||
|
||||
Order savedOrder = new Order();
|
||||
savedOrder.setId(1L);
|
||||
savedOrder.setClient(client);
|
||||
savedOrder.setNotice(notice);
|
||||
savedOrder.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
savedOrder.setStatus(Enums.OrderStatus.PENDING);
|
||||
savedOrder.setAmount(10.00);
|
||||
savedOrder.setCreatedAt(LocalDateTime.now());
|
||||
savedOrder.setUpdatedAt(LocalDateTime.now());
|
||||
|
||||
when(clientRepository.findById(1L)).thenReturn(Optional.of(client));
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.of(notice));
|
||||
when(orderRepository.save(any(Order.class))).thenReturn(savedOrder);
|
||||
|
||||
Long orderId = orderService.addOrder(orderDTO);
|
||||
|
||||
assertNotNull(orderId, "ID zamówienia nie powinno być null");
|
||||
assertEquals(1L, orderId, "ID zamówienia powinno być równe 1");
|
||||
verify(orderRepository, times(1)).save(any(Order.class));
|
||||
|
||||
System.out.println("Test dodawania zamówienia przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test zmiany statusu zamówienia")
|
||||
public void testChangeOrderStatus() {
|
||||
Long orderId = 1L;
|
||||
Enums.OrderStatus newStatus = Enums.OrderStatus.COMPLETED;
|
||||
|
||||
Order existingOrder = new Order();
|
||||
existingOrder.setId(orderId);
|
||||
existingOrder.setStatus(Enums.OrderStatus.PENDING);
|
||||
|
||||
when(orderRepository.findById(orderId)).thenReturn(Optional.of(existingOrder));
|
||||
when(orderRepository.save(any(Order.class))).thenReturn(existingOrder);
|
||||
|
||||
Long updatedOrderId = orderService.changeOrderStatus(orderId, newStatus);
|
||||
|
||||
assertNotNull(updatedOrderId, "ID zaktualizowanego zamówienia nie powinno być null");
|
||||
assertEquals(orderId, updatedOrderId, "ID zaktualizowanego zamówienia powinno być równe podanemu");
|
||||
assertEquals(newStatus, existingOrder.getStatus(), "Status zamówienia powinien zostać zaktualizowany");
|
||||
verify(orderRepository, times(1)).save(existingOrder);
|
||||
|
||||
System.out.println("Test zmiany statusu zamówienia przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania zamówienia po ID")
|
||||
public void testGetOrderById() {
|
||||
Long orderId = 1L;
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
|
||||
when(orderRepository.findById(orderId)).thenReturn(Optional.of(order));
|
||||
|
||||
Order retrievedOrder = orderService.getOrderById(orderId);
|
||||
|
||||
assertNotNull(retrievedOrder, "Pobrane zamówienie nie powinno być null");
|
||||
assertEquals(orderId, retrievedOrder.getId(), "ID pobranego zamówienia powinno być równe podanemu");
|
||||
|
||||
System.out.println("Test pobierania zamówienia po ID przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania zamówień po ID klienta")
|
||||
public void testGetOrdersByClientId() {
|
||||
Long clientId = 1L;
|
||||
List<Order> orders = List.of(new Order(), new Order());
|
||||
|
||||
when(orderRepository.findByClientId(clientId)).thenReturn(orders);
|
||||
|
||||
List<Order> retrievedOrders = orderService.getOrdersByClientId(clientId);
|
||||
|
||||
assertNotNull(retrievedOrders, "Lista zamówień nie powinna być null");
|
||||
assertEquals(2, retrievedOrders.size(), "Lista zamówień powinna zawierać 2 elementy");
|
||||
|
||||
System.out.println("Test pobierania zamówień po ID klienta przeszedł pomyślnie.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Tools;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ToolsTest {
|
||||
|
||||
@Mock
|
||||
private JwtUtil jwtUtil;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@InjectMocks
|
||||
private Tools tools;
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobieranie ID klienta z requestu - powinno zwrócić ID gdy token jest poprawny")
|
||||
void getClientIdFromRequest_shouldReturnClientIdWhenTokenValid() {
|
||||
System.out.println("Rozpoczęcie testu getClientIdFromRequest_shouldReturnClientIdWhenTokenValid");
|
||||
|
||||
String token = "valid.token.here";
|
||||
Long expectedClientId = 1L;
|
||||
|
||||
when(request.getHeader("Authorization")).thenReturn("Bearer " + token);
|
||||
when(jwtUtil.extractUserId(token)).thenReturn(expectedClientId);
|
||||
|
||||
Long result = tools.getClientIdFromRequest(request);
|
||||
|
||||
assertEquals(expectedClientId, result);
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie pobrano ID klienta z tokenu");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.controller.WishlistController;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.RequestResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.service.WishlistService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Tools;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WishlistControllerTest {
|
||||
|
||||
@Mock
|
||||
private WishlistService wishlistService;
|
||||
|
||||
@Mock
|
||||
private ClientService clientService;
|
||||
|
||||
@Mock
|
||||
private NoticeService noticeService;
|
||||
|
||||
@Mock
|
||||
private Tools tools;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@InjectMocks
|
||||
private WishlistController wishlistController;
|
||||
|
||||
private final Long testClientId = 1L;
|
||||
private final Long testNoticeId = 1L;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("[Konfiguracja] Przygotowanie środowiska testowego...");
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(testClientId);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie/Usunięcie z wishlisty - powinno zwrócić sukces gdy ogłoszenie istnieje")
|
||||
void toggleWishlist_shouldReturnSuccessWhenNoticeExists() {
|
||||
System.out.println("Rozpoczęcie testu toggleWishlist_shouldReturnSuccessWhenNoticeExists");
|
||||
|
||||
NoticeResponseDTO noticeResponse = new NoticeResponseDTO();
|
||||
noticeResponse.setNoticeId(testNoticeId);
|
||||
|
||||
when(noticeService.getNoticeById(testNoticeId)).thenReturn(noticeResponse);
|
||||
when(clientService.getClientById(testClientId)).thenReturn(new Client());
|
||||
when(noticeService.getNoticeByIdEntity(testNoticeId)).thenReturn(new Notice());
|
||||
when(wishlistService.toggleWishlist(any(), any())).thenReturn(true);
|
||||
|
||||
ResponseEntity<RequestResponseDTO> response = wishlistController.toggleWishlist(testNoticeId, request);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
assertNotNull(response.getBody());
|
||||
assertEquals("Wishlist entry added", response.getBody().getMessage());
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie obsłużono dodanie/usunięcie z wishlisty");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie/Usunięcie z wishlisty - powinno zwrócić błąd gdy ogłoszenie nie istnieje")
|
||||
void toggleWishlist_shouldReturnBadRequestWhenNoticeNotFound() {
|
||||
System.out.println("Rozpoczęcie testu toggleWishlist_shouldReturnBadRequestWhenNoticeNotFound");
|
||||
|
||||
when(noticeService.getNoticeById(testNoticeId)).thenReturn(null);
|
||||
|
||||
ResponseEntity<RequestResponseDTO> response = wishlistController.toggleWishlist(testNoticeId, request);
|
||||
|
||||
assertEquals(400, response.getStatusCode().value());
|
||||
assertNotNull(response.getBody());
|
||||
assertEquals("Notice not found", response.getBody().getMessage());
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie obsłużono brak ogłoszenia");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobieranie wishlisty - powinno zwrócić listę ogłoszeń")
|
||||
void getWishlistForClient_shouldReturnNoticeList() {
|
||||
System.out.println("Rozpoczęcie testu getWishlistForClient_shouldReturnNoticeList");
|
||||
|
||||
NoticeResponseDTO noticeResponse = new NoticeResponseDTO();
|
||||
noticeResponse.setNoticeId(testNoticeId);
|
||||
|
||||
when(wishlistService.getNoticesInWishlist(testClientId)).thenReturn(Collections.singletonList(noticeResponse));
|
||||
|
||||
List<NoticeResponseDTO> result = wishlistController.getWishlistForClient(request);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(testNoticeId, result.getFirst().getNoticeId());
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie pobrano listę ogłoszeń");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobieranie wishlisty - powinno zwrócić pustą listę gdy brak wpisów")
|
||||
void getWishlistForClient_shouldReturnEmptyListWhenNoEntries() {
|
||||
System.out.println("Rozpoczęcie testu getWishlistForClient_shouldReturnEmptyListWhenNoEntries");
|
||||
|
||||
when(wishlistService.getNoticesInWishlist(testClientId)).thenReturn(Collections.emptyList());
|
||||
|
||||
List<NoticeResponseDTO> result = wishlistController.getWishlistForClient(request);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie zwrócono pustą wishlistę");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Wishlist;
|
||||
import _11.asktpk.artisanconnectbackend.repository.WishlistRepository;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.service.WishlistService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WishlistServiceTest {
|
||||
|
||||
@Mock
|
||||
private WishlistRepository wishlistRepository;
|
||||
|
||||
@Mock
|
||||
private NoticeService noticeService;
|
||||
|
||||
@InjectMocks
|
||||
private WishlistService wishlistService;
|
||||
|
||||
private Client testClient;
|
||||
private Notice testNotice;
|
||||
private Wishlist testWishlist;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Przygotowanie danych testowych...");
|
||||
|
||||
testClient = new Client();
|
||||
testClient.setId(1L);
|
||||
testClient.setEmail("test@example.com");
|
||||
|
||||
testNotice = new Notice();
|
||||
testNotice.setIdNotice(1L);
|
||||
testNotice.setTitle("Test Notice");
|
||||
|
||||
testWishlist = new Wishlist();
|
||||
testWishlist.setId(1L);
|
||||
testWishlist.setClient(testClient);
|
||||
testWishlist.setNotice(testNotice);
|
||||
|
||||
System.out.println("[Konfiguracja] Dane testowe gotowe");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Przełączanie wishlisty - powinno dodać gdy wpis nie istnieje")
|
||||
void toggleWishlist_shouldAddWhenNotExists() {
|
||||
System.out.println("Rozpoczęcie testu toggleWishlist_shouldAddWhenNotExists");
|
||||
|
||||
when(wishlistRepository.findByClientAndNotice(testClient, testNotice)).thenReturn(Optional.empty());
|
||||
when(wishlistRepository.save(any(Wishlist.class))).thenReturn(testWishlist);
|
||||
|
||||
boolean result = wishlistService.toggleWishlist(testClient, testNotice);
|
||||
|
||||
assertTrue(result);
|
||||
verify(wishlistRepository, times(1)).save(any(Wishlist.class));
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie dodano do wishlisty");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Przełączanie wishlisty - powinno usunąć gdy wpis istnieje")
|
||||
void toggleWishlist_shouldRemoveWhenExists() {
|
||||
System.out.println("Rozpoczęcie testu toggleWishlist_shouldRemoveWhenExists");
|
||||
|
||||
when(wishlistRepository.findByClientAndNotice(testClient, testNotice)).thenReturn(Optional.of(testWishlist));
|
||||
|
||||
boolean result = wishlistService.toggleWishlist(testClient, testNotice);
|
||||
|
||||
assertFalse(result);
|
||||
verify(wishlistRepository, times(1)).delete(testWishlist);
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie usunięto z wishlisty");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobieranie ogłoszeń z wishlisty - powinno zwrócić listę ogłoszeń")
|
||||
void getNoticesInWishlist_shouldReturnNoticeList() {
|
||||
System.out.println("Rozpoczęcie testu getNoticesInWishlist_shouldReturnNoticeList");
|
||||
|
||||
List<Wishlist> wishlistEntries = new ArrayList<>();
|
||||
wishlistEntries.add(testWishlist);
|
||||
|
||||
when(wishlistRepository.findAllByClientId(1L)).thenReturn(wishlistEntries);
|
||||
when(noticeService.getNoticeById(1L)).thenReturn(new NoticeResponseDTO());
|
||||
|
||||
List<NoticeResponseDTO> result = wishlistService.getNoticesInWishlist(1L);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
|
||||
System.out.println(" Test zakończony powodzeniem: Poprawnie zwrócono listę ogłoszeń");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobieranie ogłoszeń z wishlisty - powinno zwrócić pustą listę gdy brak wpisów")
|
||||
void getNoticesInWishlist_shouldReturnEmptyListWhenNoEntries() {
|
||||
System.out.println("Rozpoczęcie testu getNoticesInWishlist_shouldReturnEmptyListWhenNoEntries");
|
||||
|
||||
when(wishlistRepository.findAllByClientId(1L)).thenReturn(new ArrayList<>());
|
||||
|
||||
List<NoticeResponseDTO> result = wishlistService.getNoticesInWishlist(1L);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie zwrócono pustą listę");
|
||||
}
|
||||
}
|
||||
BIN
src/test/resources/test.jpeg
Normal file
BIN
src/test/resources/test.jpeg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
BIN
src/test/resources/test.jpg
Normal file
BIN
src/test/resources/test.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
BIN
src/test/resources/test.png
Normal file
BIN
src/test/resources/test.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 435 KiB |
Reference in New Issue
Block a user