Compare commits
10 Commits
f7023f9c4a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 86e902bbfe | |||
| d9a8ffe4bd | |||
| c59998c113 | |||
| ff5dc5c090 | |||
| 4d7a191e8a | |||
| 7c7e82b0e6 | |||
| 7d070075d6 | |||
| b24d263f22 | |||
| a7c8f22658 | |||
| f31885c795 |
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -29,7 +30,7 @@ public class ImageController {
|
||||
private String uploadDir;
|
||||
|
||||
@PostMapping("/upload/{id}")
|
||||
public ResponseEntity<RequestResponseDTO> uploadImage(@RequestParam("file") MultipartFile file, @PathVariable("id") Long noticeId) {
|
||||
public ResponseEntity<RequestResponseDTO> uploadImage(@RequestParam("file") MultipartFile file, @PathVariable("id") Long noticeId, @Param("isMainImage") Boolean isMainImage) {
|
||||
try {
|
||||
if(file.isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(new RequestResponseDTO("File is empty"));
|
||||
@@ -44,10 +45,11 @@ public class ImageController {
|
||||
}
|
||||
|
||||
String newImageName = imageService.saveImageToStorage(uploadDir, file);
|
||||
imageService.addImageNameToDB(newImageName, noticeId);
|
||||
imageService.addImageNameToDB(newImageName, noticeId, isMainImage);
|
||||
|
||||
return ResponseEntity.ok(new RequestResponseDTO("Image uploaded successfully with new name: " + newImageName));
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).body(new RequestResponseDTO(e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
public class ImageRequestDTO {
|
||||
public Resource image;
|
||||
public Long noticeId;
|
||||
public boolean isMainImage;
|
||||
}
|
||||
@@ -40,10 +40,11 @@ public class ImageService {
|
||||
return uniqueFileName;
|
||||
}
|
||||
|
||||
public void addImageNameToDB(String filename, Long noticeId) {
|
||||
public void addImageNameToDB(String filename, Long noticeId, boolean isMainImage) {
|
||||
Image image = new Image();
|
||||
image.setImageName(filename);
|
||||
image.setNoticeId(noticeId);
|
||||
image.setMainImage(isMainImage);
|
||||
imageRepository.save(image);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,39 +1,33 @@
|
||||
spring.application.name=ArtisanConnectBackend
|
||||
|
||||
## PostgreSQL
|
||||
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
|
||||
spring.datasource.url=${DB_URL:jdbc:postgresql://db:5432/postgres}
|
||||
spring.datasource.username=${DB_USER:postgres}
|
||||
spring.datasource.password=${DB_PASS:postgres}
|
||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
spring.datasource.username=postgres
|
||||
spring.datasource.password=postgres
|
||||
|
||||
#initial data for db injection
|
||||
spring.sql.init.data-locations=classpath:sql/data.sql
|
||||
spring.sql.init.mode=always
|
||||
spring.jpa.defer-datasource-initialization=true
|
||||
|
||||
# create and drop table, good for testing, production set to none or comment it
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
|
||||
file.upload-dir=/Users/andsol/Desktop/uploads
|
||||
spring.servlet.multipart.max-file-size=10MB
|
||||
spring.servlet.multipart.max-request-size=10MB
|
||||
file.upload-dir=${IMAGES_UPLOAD_DIR:/app/images}
|
||||
spring.servlet.multipart.max-file-size=${MAX_FILE_SIZE:10MB}
|
||||
spring.servlet.multipart.max-request-size=${MAX_REQUEST_SIZE:10MB}
|
||||
|
||||
spring.mail.host=smtp.sendgrid.net
|
||||
spring.mail.port=587
|
||||
spring.mail.username=apikey
|
||||
spring.mail.password=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
|
||||
spring.mail.properties.mail.smtp.auth=true
|
||||
spring.mail.properties.mail.smtp.starttls.enable=true
|
||||
spring.mail.host=${MAIL_HOST}
|
||||
spring.mail.port=${MAIL_PORT}
|
||||
spring.mail.username=${MAIL_USER}
|
||||
spring.mail.password=${MAIL_PASSWORD}
|
||||
|
||||
tpay.clientId = 01JQKC048X62ST9V59HNRSXD92-01JQKC2CQHPYXQFSFX8BKC24BX
|
||||
tpay.clientSecret = 44898642be53381cdcc47f3e44bf5a15e592f5d270fc3a6cf6fb81a8b8ebffb9
|
||||
tpay.authUrl = https://openapi.sandbox.tpay.com/oauth/auth
|
||||
tpay.transactionUrl = https://openapi.sandbox.tpay.com/transactions
|
||||
tpay.securityCode = )IY7E)YSM!A)Q6O-GN#U7U_33s9qObk8
|
||||
tpay.clientId=${TPAY_CLIENT_ID}
|
||||
tpay.clientSecret=${TPAY_SECRET}
|
||||
tpay.authUrl=${TPAY_AUTH_URL}
|
||||
tpay.transactionUrl=${TPAY_TRANSACTION_URL}
|
||||
tpay.securityCode = ${TPAY_SECURITY_CODE}
|
||||
|
||||
#jwt settings
|
||||
jwt.secret=DIXLsOs3FKmCAQwISd0SKsHMXJrPl3IKIRkVlkOvYW7kEcdUTbxh8zFe1B3eZWkY
|
||||
jwt.expiration=300000
|
||||
jwt.secret=${JWT_SECRET}
|
||||
jwt.expiration=1200000
|
||||
|
||||
logging.file.name=logs/payment-notifications.log
|
||||
logging.level.TpayLogger=INFO
|
||||
@@ -5,11 +5,11 @@ VALUES
|
||||
|
||||
INSERT INTO clients (email, first_name, last_name, password, role_id)
|
||||
VALUES
|
||||
('dignissim.tempor.arcu@aol.ca', 'Diana', 'Harrison', 'password', 1),
|
||||
('john.doe@example.com', 'John', 'Doe', 'password123', 2),
|
||||
('jane.smith@example.com', 'Jane', 'Smith', 'securepass', 1),
|
||||
('michael.brown@example.com', 'Michael', 'Brown', 'mypassword', 1),
|
||||
('emily.jones@example.com', 'Emily', 'Jones', 'passw0rd', 1);
|
||||
('dignissim.tempor.arcu@aol.ca', 'Diana', 'Harrison', '', 1),
|
||||
('john.doe@example.com', 'John', 'Doe', '', 2),
|
||||
('jane.smith@example.com', 'Jane', 'Smith', '', 1),
|
||||
('michael.brown@example.com', 'Michael', 'Brown', '', 1),
|
||||
('emily.jones@example.com', 'Emily', 'Jones', '', 1);
|
||||
|
||||
|
||||
INSERT INTO notice (title, description, client_id, price, category, status, publish_date) VALUES
|
||||
|
||||
@@ -1,21 +1,12 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.CategoriesDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.WishlistDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Wishlist;
|
||||
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.NoticeRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.WishlistRepository;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import _11.asktpk.artisanconnectbackend.service.ImageService;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.service.WishlistService;
|
||||
import _11.asktpk.artisanconnectbackend.service.*;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.junit.jupiter.api.*;
|
||||
@@ -23,16 +14,15 @@ 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.dao.DataIntegrityViolationException;
|
||||
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.mockito.Mockito;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
|
||||
@@ -41,8 +31,9 @@ import java.lang.reflect.Constructor;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.Comparator;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -57,486 +48,147 @@ class ArtisanConnectBackendApplicationTests {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(ArtisanConnectBackendApplicationTests.class);
|
||||
|
||||
@LocalServerPort
|
||||
private final int port;
|
||||
|
||||
private final ClientService clientService;
|
||||
private final TestRestTemplate restTemplate;
|
||||
|
||||
@Autowired
|
||||
public ArtisanConnectBackendApplicationTests(ClientService clientService, @LocalServerPort int port) {
|
||||
this.clientService = clientService;
|
||||
this.port = port;
|
||||
this.restTemplate = new TestRestTemplate();
|
||||
}
|
||||
|
||||
|
||||
@Nested
|
||||
@DisplayName("Testy jednostkowe ClientService")
|
||||
class ClientServiceTest {
|
||||
|
||||
private final ClientRepository clientRepository;
|
||||
private final ClientService clientService;
|
||||
|
||||
ClientServiceTest(ClientRepository clientRepository, ClientService clientService) {
|
||||
logger.info("Inicjalizacja mocków dla ClientService");
|
||||
this.clientRepository = clientRepository;
|
||||
this.clientService = clientService;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie mapować klientów na ClientDTO")
|
||||
void testClientMappingToDTO() {
|
||||
logger.info("Tworzenie danych klientów...");
|
||||
Client client = createTestClient("Jan", "Kowalski");
|
||||
when(clientRepository.findAll()).thenReturn(List.of(client));
|
||||
|
||||
logger.info("Wywołanie metody getAllClients...");
|
||||
List<ClientDTO> clientDTOList = clientService.getAllClients();
|
||||
|
||||
assertThat(clientDTOList).hasSize(1);
|
||||
assertThat(clientDTOList.get(0).getFirstName()).isEqualTo("Jan");
|
||||
verify(clientRepository, times(1)).findAll();
|
||||
logger.info("Test zakończony poprawnie");
|
||||
}
|
||||
|
||||
private Client createTestClient(String firstName, String lastName) {
|
||||
Client client = new Client();
|
||||
client.setFirstName(firstName);
|
||||
client.setLastName(lastName);
|
||||
client.setEmail(firstName.toLowerCase() + "." + lastName.toLowerCase() + "@example.com");
|
||||
client.setRole(clientService.getUserRole());
|
||||
return client;
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Testy integracyjne ClientController")
|
||||
class ClientControllerTest {
|
||||
|
||||
private final int port;
|
||||
private final TestRestTemplate restTemplate;
|
||||
private final ClientService clientService;
|
||||
private final NoticeService noticeService;
|
||||
private final NoticeRepository noticeRepository;
|
||||
private final Logger logger = LogManager.getLogger(ClientControllerTest.class);
|
||||
|
||||
@Autowired
|
||||
public ClientControllerTest(
|
||||
@LocalServerPort int port,
|
||||
TestRestTemplate restTemplate,
|
||||
ClientService clientService,
|
||||
NoticeService noticeService,
|
||||
NoticeRepository noticeRepository) {
|
||||
this.port = port;
|
||||
this.restTemplate = restTemplate;
|
||||
this.clientService = clientService;
|
||||
this.noticeService = noticeService;
|
||||
this.noticeRepository = noticeRepository;
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void cleanDatabase() {
|
||||
|
||||
noticeRepository.deleteAll();
|
||||
|
||||
clientService.getAllClients().forEach(client -> {
|
||||
try {
|
||||
clientService.deleteClient(client.getId());
|
||||
} catch (Exception e) {
|
||||
logger.error("Błąd podczas usuwania klienta: {}", e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private boolean hasNotices(Long clientId) {
|
||||
return noticeService.getAllNotices().stream()
|
||||
.anyMatch(notice -> notice.getClientId().equals(clientId));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie usunąć klienta z powiązanymi ogłoszeniami")
|
||||
void shouldDeleteClientWithNotices() {
|
||||
ClientDTO client = clientService.addClient(createTestDTO("client@example.com", "Jan", "Kowalski"));
|
||||
|
||||
NoticeDTO notice = new NoticeDTO();
|
||||
notice.setClientId(client.getId());
|
||||
notice.setTitle("Test Notice");
|
||||
Long noticeId = noticeService.addNotice(notice);
|
||||
|
||||
ResponseEntity<Void> deleteNoticeResponse = restTemplate.exchange(
|
||||
createURLWithPort("/api/v1/notices/delete/" + noticeId),
|
||||
HttpMethod.DELETE,
|
||||
null,
|
||||
Void.class
|
||||
);
|
||||
assertThat(deleteNoticeResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
|
||||
ResponseEntity<Void> deleteClientResponse = restTemplate.exchange(
|
||||
createURLWithPort("/api/v1/clients/delete/" + client.getId()),
|
||||
HttpMethod.DELETE,
|
||||
null,
|
||||
Void.class
|
||||
);
|
||||
|
||||
assertThat(deleteClientResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(clientService.clientExists(client.getId())).isFalse();
|
||||
assertThat(noticeService.noticeExists(noticeId)).isFalse();
|
||||
}
|
||||
@Autowired
|
||||
private ClientRepository clientRepository;
|
||||
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwracać wszystkich klientów")
|
||||
void shouldReturnAllClients() {
|
||||
ClientDTO client1 = clientService.addClient(createTestDTO("client1@example.com", "Anna", "Nowak"));
|
||||
ClientDTO client2 = clientService.addClient(createTestDTO("client2@example.com", "Adam", "Kowalski"));
|
||||
|
||||
ResponseEntity<ClientDTO[]> response = restTemplate.getForEntity(
|
||||
createURLWithPort("/api/v1/clients/get/all"),
|
||||
ClientDTO[].class
|
||||
);
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull();
|
||||
assertThat(response.getBody()).hasSize(2);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić błąd przy próbie usunięcia klienta z powiązanymi ogłoszeniami bez kaskady")
|
||||
void shouldFailWhenDeletingClientWithNoticesWithoutCascade() {
|
||||
noticeService.getAllNotices().forEach(n -> noticeService.deleteNotice(n.getNoticeId()));
|
||||
clientService.getAllClients().forEach(c -> clientService.deleteClient(c.getId()));
|
||||
|
||||
ClientDTO client = clientService.addClient(createTestDTO("client@example.com", "Jan", "Kowalski"));
|
||||
|
||||
NoticeDTO notice = new NoticeDTO();
|
||||
notice.setClientId(client.getId());
|
||||
notice.setTitle("Test Notice");
|
||||
noticeService.addNotice(notice);
|
||||
|
||||
try {
|
||||
clientService.deleteClient(client.getId());
|
||||
fail("Powinien zostać rzucony wyjątek DataIntegrityViolationException");
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
// Oczekiwany wyjątek
|
||||
assertThat(e.getMessage()).contains("could not execute statement");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie usunąć klienta bez powiązanych ogłoszeń")
|
||||
void shouldDeleteClientWithoutNotices() {
|
||||
ClientDTO client = clientService.addClient(createTestDTO("client@example.com", "Jan", "Kowalski"));
|
||||
|
||||
ResponseEntity<Void> deleteResponse = restTemplate.exchange(
|
||||
createURLWithPort("/api/v1/clients/delete/" + client.getId()),
|
||||
HttpMethod.DELETE,
|
||||
null,
|
||||
Void.class
|
||||
);
|
||||
|
||||
assertThat(deleteResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(clientService.clientExists(client.getId())).isFalse();
|
||||
}
|
||||
|
||||
private ClientDTO createTestDTO(String email, String firstName, String lastName) {
|
||||
ClientDTO clientDTO = new ClientDTO();
|
||||
clientDTO.setEmail(email);
|
||||
clientDTO.setFirstName(firstName);
|
||||
clientDTO.setLastName(lastName);
|
||||
clientDTO.setRole("USER");
|
||||
return clientDTO;
|
||||
}
|
||||
|
||||
private String createURLWithPort(String uri) {
|
||||
return "http://localhost:" + port + uri;
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Testy jednostkowe NoticeService")
|
||||
class NoticeServiceUnitTest {
|
||||
|
||||
private final NoticeRepository noticeRepository;
|
||||
private final ClientRepository clientRepository;
|
||||
private final NoticeService noticeService;
|
||||
|
||||
NoticeServiceUnitTest() {
|
||||
this.noticeRepository = mock(NoticeRepository.class);
|
||||
this.clientRepository = mock(ClientRepository.class);
|
||||
this.noticeService = new NoticeService(
|
||||
noticeRepository,
|
||||
clientRepository,
|
||||
null,
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie dodać ogłoszenie")
|
||||
void shouldAddNoticeSuccessfully() {
|
||||
Client client = createTestClient("test@example.com", "Anna", "Kowalska");
|
||||
when(clientRepository.findById(1L)).thenReturn(Optional.of(client));
|
||||
|
||||
NoticeDTO noticeDTO = new NoticeDTO();
|
||||
noticeDTO.setClientId(1L);
|
||||
noticeDTO.setTitle("Test Notice");
|
||||
noticeDTO.setDescription("Opis ogłoszenia");
|
||||
noticeDTO.setPrice(100.0);
|
||||
|
||||
Notice notice = new Notice();
|
||||
notice.setIdNotice(1L);
|
||||
|
||||
when(noticeRepository.save(any(Notice.class))).thenReturn(notice);
|
||||
|
||||
Long savedNoticeId = noticeService.addNotice(noticeDTO);
|
||||
|
||||
assertThat(savedNoticeId).isEqualTo(1L);
|
||||
verify(noticeRepository, times(1)).save(any(Notice.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić wyjątek, gdy klient dla ogłoszenia nie istnieje")
|
||||
void shouldThrowExceptionWhenClientNotFound() {
|
||||
NoticeDTO noticeDTO = new NoticeDTO();
|
||||
noticeDTO.setClientId(1L);
|
||||
|
||||
when(clientRepository.findById(1L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(EntityNotFoundException.class, () -> noticeService.addNotice(noticeDTO));
|
||||
}
|
||||
|
||||
private Client createTestClient(String email, String firstName, String lastName) {
|
||||
Client client = new Client();
|
||||
client.setId(1L);
|
||||
client.setEmail(email);
|
||||
client.setFirstName(firstName);
|
||||
client.setLastName(lastName);
|
||||
return client;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Nested
|
||||
@DisplayName("Testy integracyjne ImageService")
|
||||
class ImageServiceTest {
|
||||
|
||||
private final ImageRepository imageRepository;
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie zapisać obraz w magazynie plików")
|
||||
void shouldSaveImageToStorage() throws IOException {
|
||||
MultipartFile file = mock(MultipartFile.class);
|
||||
when(file.getOriginalFilename()).thenReturn("test.jpg");
|
||||
when(file.getInputStream()).thenReturn(Files.newInputStream(Path.of("src/test/resources/test.jpg")));
|
||||
|
||||
String uploadDirectory = "upload_dir";
|
||||
Path uploadPath = Path.of(uploadDirectory);
|
||||
Files.createDirectories(uploadPath);
|
||||
|
||||
String savedFileName = imageService.saveImageToStorage(uploadDirectory, file);
|
||||
|
||||
assertTrue(savedFileName.contains(".jpg"));
|
||||
assertTrue(Files.exists(uploadPath.resolve(savedFileName)));
|
||||
|
||||
Files.deleteIfExists(uploadPath.resolve(savedFileName));
|
||||
@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ć nazwę obrazu do bazy danych")
|
||||
void shouldAddImageNameToDB() {
|
||||
String filename = UUID.randomUUID() + "test.jpg";
|
||||
Long noticeId = 1L;
|
||||
@DisplayName("Powinien poprawnie zapisać obraz w magazynie plików")
|
||||
void shouldSaveImageToStorage() throws IOException {
|
||||
logger.info("Test zapisu obrazu - rozpoczęcie");
|
||||
|
||||
imageService.addImageNameToDB(filename, noticeId);
|
||||
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);
|
||||
|
||||
verify(imageRepository, times(1)).save(Mockito.any(Image.class));
|
||||
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 {
|
||||
Path imagePath = Path.of("src/test/resources/test.jpg");
|
||||
Resource resource = imageService.getImage("src/test/resources", "test.jpg");
|
||||
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 instanceof UrlResource);
|
||||
assertTrue(Files.exists(imagePath));
|
||||
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() {
|
||||
Exception exception = assertThrows(IOException.class, () -> {
|
||||
imageService.getImage("invalid/path", "missing.jpg");
|
||||
});
|
||||
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 i bazy danych")
|
||||
@DisplayName("Powinien poprawnie usuwać obraz z magazynu plików")
|
||||
void shouldDeleteImage() throws IOException {
|
||||
Path imagePath = Files.createTempFile("temp-dir", "temp-image.jpg");
|
||||
String imageName = imagePath.getFileName().toString();
|
||||
String imageDirectory = imagePath.getParent().toString();
|
||||
logger.info("Test usuwania obrazu - rozpoczęcie");
|
||||
|
||||
Image image = new Image();
|
||||
image.setImageName(imageName);
|
||||
when(imageRepository.existsImageByImageNameEqualsIgnoreCase(imageName)).thenReturn(true);
|
||||
final String testFileName = "test-delete.jpg";
|
||||
final Path testFilePath = testDirectory.resolve(testFileName);
|
||||
Files.createFile(testFilePath);
|
||||
logger.debug("Utworzono testowy plik: {}", testFilePath);
|
||||
|
||||
imageService.deleteImage(imageDirectory, imageName);
|
||||
when(imageRepository.existsImageByImageNameEqualsIgnoreCase(testFileName)).thenReturn(true);
|
||||
|
||||
assertFalse(Files.exists(imagePath));
|
||||
verify(imageRepository, times(1)).deleteByImageNameEquals(imageName);
|
||||
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 dla podanego ogłoszenia")
|
||||
@DisplayName("Powinien poprawnie zwrócić listę nazw obrazów")
|
||||
void shouldGetImagesListForNotice() throws Exception {
|
||||
Long noticeId = 1L;
|
||||
List<Image> images = List.of(
|
||||
createTestImage(1L, noticeId, "image1.jpg"),
|
||||
createTestImage(2L, noticeId, "image2.jpg")
|
||||
);
|
||||
when(imageRepository.findByNoticeId(noticeId)).thenReturn(images);
|
||||
logger.info("Test pobierania listy obrazów - rozpoczęcie");
|
||||
|
||||
List<String> imageNames = imageService.getImagesList(noticeId);
|
||||
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());
|
||||
|
||||
assertThat(imageNames).hasSize(2);
|
||||
assertThat(imageNames).containsExactly("image1.jpg", "image2.jpg");
|
||||
}
|
||||
when(imageRepository.findByNoticeId(noticeId)).thenReturn(mockImages);
|
||||
logger.debug("Skonfigurowano mock repository dla noticeId: {}", noticeId);
|
||||
|
||||
private Image createTestImage(Long id, Long noticeId, String imageName) {
|
||||
Image image = new Image();
|
||||
image.setId(id);
|
||||
image.setNoticeId(noticeId);
|
||||
image.setImageName(imageName);
|
||||
return image;
|
||||
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 integracyjne WishlistService")
|
||||
class WishlistServiceTest {
|
||||
|
||||
private final WishlistRepository wishlistRepository;
|
||||
private final NoticeService noticeService;
|
||||
private final WishlistService wishlistService;
|
||||
|
||||
WishlistServiceTest() {
|
||||
this.wishlistRepository = mock(WishlistRepository.class);
|
||||
this.noticeService = mock(NoticeService.class);
|
||||
this.wishlistService = new WishlistService(wishlistRepository, noticeService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie zwrócić wishlist dla klienta")
|
||||
void shouldGetWishlistForClient() {
|
||||
Long clientId = 1L;
|
||||
Wishlist wishlist1 = createTestWishlist(1L, clientId, 10L);
|
||||
Wishlist wishlist2 = createTestWishlist(2L, clientId, 20L);
|
||||
|
||||
when(wishlistRepository.findAllByClientId(clientId)).thenReturn(List.of(wishlist1, wishlist2));
|
||||
|
||||
List<WishlistDTO> result = wishlistService.getWishlistForClientId(clientId);
|
||||
|
||||
assertThat(result).hasSize(2);
|
||||
assertThat(result.get(0).getNoticeId()).isEqualTo(10L);
|
||||
verify(wishlistRepository, times(1)).findAllByClientId(clientId);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie dodać lub usunąć element z wishlist")
|
||||
void shouldToggleWishlist() {
|
||||
Client client = createTestClient(1L, "test@example.com");
|
||||
Notice notice = createTestNotice(10L);
|
||||
|
||||
// Scenariusz 1: Element istnieje i powinien zostać usunięty
|
||||
when(wishlistRepository.findByClientAndNotice(client, notice)).thenReturn(Optional.of(new Wishlist()));
|
||||
|
||||
boolean removed = wishlistService.toggleWishlist(client, notice);
|
||||
|
||||
assertThat(removed).isFalse();
|
||||
verify(wishlistRepository, times(1)).delete(any(Wishlist.class));
|
||||
|
||||
// Scenariusz 2: Element nie istnieje i powinien zostać dodany
|
||||
when(wishlistRepository.findByClientAndNotice(client, notice)).thenReturn(Optional.empty());
|
||||
|
||||
boolean added = wishlistService.toggleWishlist(client, notice);
|
||||
|
||||
assertThat(added).isTrue();
|
||||
verify(wishlistRepository, times(1)).save(any(Wishlist.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić listę ogłoszeń w wishlist klienta")
|
||||
void shouldGetNoticesInWishlist() {
|
||||
Long clientId = 1L;
|
||||
Wishlist wishlist1 = createTestWishlist(1L, clientId, 10L);
|
||||
Wishlist wishlist2 = createTestWishlist(2L, clientId, 20L);
|
||||
|
||||
when(wishlistRepository.findAllByClientId(clientId)).thenReturn(List.of(wishlist1, wishlist2));
|
||||
when(noticeService.getNoticeById(10L)).thenReturn(createNoticeDTO(10L, "Ogłoszenie 1"));
|
||||
when(noticeService.getNoticeById(20L)).thenReturn(createNoticeDTO(20L, "Ogłoszenie 2"));
|
||||
|
||||
List<NoticeDTO> result = wishlistService.getNoticesInWishlist(clientId);
|
||||
|
||||
assertThat(result).hasSize(2);
|
||||
assertThat(result.get(0).getNoticeId()).isEqualTo(10L);
|
||||
assertThat(result.get(1).getNoticeId()).isEqualTo(20L);
|
||||
}
|
||||
|
||||
private Wishlist createTestWishlist(Long id, Long clientId, Long noticeId) {
|
||||
Wishlist wishlist = new Wishlist();
|
||||
wishlist.setId(id);
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(clientId);
|
||||
wishlist.setClient(client);
|
||||
|
||||
Notice notice = new Notice();
|
||||
notice.setIdNotice(noticeId);
|
||||
wishlist.setNotice(notice);
|
||||
|
||||
return wishlist;
|
||||
}
|
||||
|
||||
private Client createTestClient(Long id, String email) {
|
||||
Client client = new Client();
|
||||
client.setId(id);
|
||||
client.setEmail(email);
|
||||
return client;
|
||||
}
|
||||
|
||||
private Notice createTestNotice(Long noticeId) {
|
||||
Notice notice = new Notice();
|
||||
notice.setIdNotice(noticeId);
|
||||
return notice;
|
||||
}
|
||||
|
||||
private NoticeDTO createNoticeDTO(Long noticeId, String title) {
|
||||
NoticeDTO noticeDTO = new NoticeDTO();
|
||||
noticeDTO.setNoticeId(noticeId);
|
||||
noticeDTO.setTitle(title);
|
||||
return noticeDTO;
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Testy dla VariablesController")
|
||||
@Transactional
|
||||
class VariablesControllerTest {
|
||||
|
||||
private final int port;
|
||||
@@ -546,40 +198,101 @@ class ArtisanConnectBackendApplicationTests {
|
||||
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() {
|
||||
String url = createURLWithPort("/api/v1/vars/categories");
|
||||
logger.info("Test pobierania kategorii - rozpoczęcie");
|
||||
String token = registerAndGetJwtToken(
|
||||
"categories"
|
||||
);
|
||||
logger.debug("Otrzymano token autoryzacyjny");
|
||||
|
||||
ResponseEntity<CategoriesDTO[]> response = restTemplate.getForEntity(url, CategoriesDTO[].class);
|
||||
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");
|
||||
|
||||
ResponseEntity<Enums.Status[]> response = restTemplate.getForEntity(url, Enums.Status[].class);
|
||||
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();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić role")
|
||||
void shouldGetRoles() {
|
||||
String url = createURLWithPort("/api/v1/vars/roles");
|
||||
|
||||
ResponseEntity<Enums.Role[]> response = restTemplate.getForEntity(url, Enums.Role[].class);
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull().isNotEmpty();
|
||||
}
|
||||
|
||||
private String createURLWithPort(String uri) {
|
||||
return "http://localhost:" + port + uri;
|
||||
@@ -587,4 +300,142 @@ class ArtisanConnectBackendApplicationTests {
|
||||
}
|
||||
|
||||
|
||||
|
||||
@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());
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -29,6 +29,8 @@ public class ClientServiceTest {
|
||||
@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");
|
||||
@@ -43,17 +45,20 @@ public class ClientServiceTest {
|
||||
|
||||
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 przeszedł pomyślnie.");
|
||||
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() {
|
||||
// Przygotowanie danych
|
||||
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");
|
||||
@@ -63,29 +68,35 @@ public class ClientServiceTest {
|
||||
|
||||
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 (klient istnieje) przeszedł pomyślnie.");
|
||||
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 klienta po ID (klient nie istnieje) przeszedł pomyślnie.");
|
||||
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);
|
||||
|
||||
@@ -93,16 +104,18 @@ public class ClientServiceTest {
|
||||
|
||||
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 przeszedł pomyślnie.");
|
||||
System.out.println("Test pobierania klienta po emailu (" + email + ") zakończony sukcesem.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test dodawania klienta")
|
||||
public void testAddClient() {
|
||||
// Przygotowanie danych
|
||||
System.out.println("Rozpoczęcie testu: testAddClient - Test dodawania nowego klienta");
|
||||
|
||||
ClientDTO clientDTO = new ClientDTO();
|
||||
clientDTO.setEmail("newclient@example.com");
|
||||
clientDTO.setRole("USER");
|
||||
@@ -115,16 +128,19 @@ public class ClientServiceTest {
|
||||
|
||||
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 przeszedł pomyślnie.");
|
||||
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");
|
||||
@@ -142,41 +158,49 @@ public class ClientServiceTest {
|
||||
|
||||
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 przeszedł pomyślnie.");
|
||||
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 klienta (klient nie istnieje) przeszedł pomyślnie.");
|
||||
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 przeszedł pomyślnie.");
|
||||
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");
|
||||
@@ -187,8 +211,24 @@ public class ClientServiceTest {
|
||||
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");
|
||||
@@ -196,7 +236,6 @@ public class ClientServiceTest {
|
||||
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 przeszedł pomyślnie.");
|
||||
System.out.println("Test konwersji encji do DTO zakończony sukcesem. Wszystkie pola zostały poprawnie zmapowane.");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ 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;
|
||||
@@ -28,13 +29,13 @@ import static org.mockito.Mockito.*;
|
||||
class NoticeControllerTest {
|
||||
|
||||
@Mock
|
||||
private final NoticeService noticeService = mock(NoticeService.class);
|
||||
private NoticeService noticeService;
|
||||
|
||||
@Mock
|
||||
private final ClientService clientService = mock(ClientService.class);
|
||||
private ClientService clientService;
|
||||
|
||||
@Mock
|
||||
private final Tools tools = mock(Tools.class);
|
||||
private Tools tools;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
@@ -47,7 +48,7 @@ class NoticeControllerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Inicjalizacja danych testowych przed każdym testem");
|
||||
System.out.println("Inicjalizacja danych testowych...");
|
||||
|
||||
sampleNotice = new NoticeResponseDTO();
|
||||
sampleNotice.setNoticeId(1L);
|
||||
@@ -69,53 +70,43 @@ class NoticeControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie wszystkich ogłoszeń")
|
||||
void getAllNotices_ShouldReturnListOfNotices() {
|
||||
System.out.println("Test: getAllNotices_ShouldReturnListOfNotices - powinien zwrócić listę ogłoszeń");
|
||||
|
||||
when(noticeService.getAllNotices()).thenReturn(List.of(sampleNotice));
|
||||
|
||||
List<NoticeResponseDTO> result = noticeController.getAllNotices();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(sampleNotice.getNoticeId(), result.getFirst().getNoticeId());
|
||||
|
||||
System.out.println("Pomyślnie zwrócono listę ogłoszeń");
|
||||
System.out.println("Test GET /notices zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie istniejącego ogłoszenia")
|
||||
void getNoticeById_WhenNoticeExists_ShouldReturnNotice() {
|
||||
System.out.println("Test: getNoticeById_WhenNoticeExists_ShouldReturnNotice - powinien zwrócić ogłoszenie gdy istnieje");
|
||||
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.getNoticeById(1L)).thenReturn(sampleNotice);
|
||||
|
||||
ResponseEntity<?> response = noticeController.getNoticeById(1L);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
assertNotNull(response.getBody());
|
||||
assertEquals(sampleNotice, response.getBody());
|
||||
|
||||
System.out.println("Pomyślnie zwrócono istniejące ogłoszenie");
|
||||
System.out.println("Test GET /notices/{id} (istniejące) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie nieistniejącego ogłoszenia")
|
||||
void getNoticeById_WhenNoticeNotExists_ShouldReturnNotFound() {
|
||||
System.out.println("Test: getNoticeById_WhenNoticeNotExists_ShouldReturnNotFound - powinien zwrócić 404 gdy ogłoszenie nie istnieje");
|
||||
|
||||
when(noticeService.noticeExists(1L)).thenReturn(false);
|
||||
|
||||
ResponseEntity<?> response = noticeController.getNoticeById(1L);
|
||||
|
||||
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
|
||||
|
||||
System.out.println("Pomyślnie zwrócono status 404 dla nieistniejącego ogłoszenia");
|
||||
System.out.println("Test GET /notices/{id} (nieistniejące) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie poprawnego ogłoszenia")
|
||||
void addNotice_WithValidData_ShouldCreateNotice() {
|
||||
System.out.println("Test: addNotice_WithValidData_ShouldCreateNotice - powinien utworzyć nowe ogłoszenie przy poprawnych danych");
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(clientService.clientExists(1L)).thenReturn(true);
|
||||
when(noticeService.addNotice(any(NoticeRequestDTO.class))).thenReturn(1L);
|
||||
@@ -123,17 +114,12 @@ class NoticeControllerTest {
|
||||
ResponseEntity<NoticeAdditionDTO> response = noticeController.addNotice(sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.CREATED, response.getStatusCode());
|
||||
assertNotNull(response.getBody());
|
||||
assertEquals(1L, response.getBody().getNoticeId());
|
||||
assertEquals("Dodano ogłoszenie.", response.getBody().getMessage());
|
||||
|
||||
System.out.println("Pomyślnie utworzono nowe ogłoszenie");
|
||||
System.out.println("Test POST /notices (poprawne dane) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie ogłoszenia z błędną kategorią")
|
||||
void addNotice_WithInvalidCategory_ShouldReturnBadRequest() {
|
||||
System.out.println("Test: addNotice_WithInvalidCategory_ShouldReturnBadRequest - powinien zwrócić błąd dla nieprawidłowej kategorii");
|
||||
|
||||
sampleNoticeRequest.setCategory(null);
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
@@ -142,32 +128,24 @@ class NoticeControllerTest {
|
||||
ResponseEntity<NoticeAdditionDTO> response = noticeController.addNotice(sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
|
||||
assertNotNull(response.getBody());
|
||||
assertEquals("Nie ma takiej kategorii", response.getBody().getMessage());
|
||||
|
||||
System.out.println("Pomyślnie zwrócono błąd dla nieprawidłowej kategorii");
|
||||
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() {
|
||||
System.out.println("Test: addNotice_WhenClientNotExists_ShouldReturnBadRequest - powinien zwrócić błąd gdy klient nie istnieje");
|
||||
|
||||
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());
|
||||
assertNotNull(response.getBody());
|
||||
assertTrue(response.getBody().getMessage().contains("Nie znaleziono klienta o ID:"));
|
||||
|
||||
System.out.println("Pomyślnie zwrócono błąd dla nieistniejącego klienta");
|
||||
System.out.println("Test POST /notices (nieistniejący klient) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Aktualizacja własnego ogłoszenia")
|
||||
void editNotice_WhenNoticeExistsAndOwnedByClient_ShouldUpdateNotice() {
|
||||
System.out.println("Test: editNotice_WhenNoticeExistsAndOwnedByClient_ShouldUpdateNotice - powinien zaktualizować ogłoszenie gdy istnieje i należy do klienta");
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.isNoticeOwnedByClient(1L, 1L)).thenReturn(true);
|
||||
@@ -176,16 +154,12 @@ class NoticeControllerTest {
|
||||
ResponseEntity<Object> response = noticeController.editNotice(1L, sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
assertNotNull(response.getBody());
|
||||
assertEquals(sampleNotice, response.getBody());
|
||||
|
||||
System.out.println("Pomyślnie zaktualizowano ogłoszenie należące do klienta");
|
||||
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() {
|
||||
System.out.println("Test: editNotice_WhenNoticeNotOwnedByClient_ShouldReturnForbidden - powinien zwrócić błąd 403 gdy ogłoszenie nie należy do klienta");
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(2L);
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.isNoticeOwnedByClient(1L, 2L)).thenReturn(false);
|
||||
@@ -193,16 +167,12 @@ class NoticeControllerTest {
|
||||
ResponseEntity<Object> response = noticeController.editNotice(1L, sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
|
||||
assertNotNull(response.getBody());
|
||||
assertTrue(((RequestResponseDTO) response.getBody()).getMessage().contains("Nie masz uprawnień"));
|
||||
|
||||
System.out.println("Pomyślnie zwrócono błąd 403 dla próby edycji nie swojego ogłoszenia");
|
||||
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() {
|
||||
System.out.println("Test: deleteNotice_WhenNoticeExistsAndOwnedByClient_ShouldDeleteNotice - powinien usunąć ogłoszenie gdy istnieje i należy do klienta");
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.isNoticeOwnedByClient(1L, 1L)).thenReturn(true);
|
||||
@@ -210,12 +180,7 @@ class NoticeControllerTest {
|
||||
ResponseEntity<RequestResponseDTO> response = noticeController.deleteNotice(1L, request);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
assertNotNull(response.getBody());
|
||||
assertTrue(response.getBody().getMessage().contains("Pomyślnie usunięto"));
|
||||
|
||||
verify(noticeService, times(1)).deleteNotice(1L);
|
||||
|
||||
System.out.println("Pomyślnie usunięto ogłoszenie należące do klienta");
|
||||
System.out.println("Test DELETE /notices/{id} (własne ogłoszenie) zakończony sukcesem");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,11 +5,11 @@ 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.ImageService;
|
||||
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;
|
||||
@@ -28,20 +28,19 @@ import static org.mockito.Mockito.*;
|
||||
class NoticeServiceTest {
|
||||
|
||||
@Mock
|
||||
private final NoticeRepository noticeRepository = mock(NoticeRepository.class);
|
||||
private NoticeRepository noticeRepository;
|
||||
|
||||
@Mock
|
||||
private final ClientRepository clientRepository = mock(ClientRepository.class);
|
||||
|
||||
private ClientRepository clientRepository;
|
||||
|
||||
@Mock
|
||||
private final AttributesRepository attributesRepository = mock(AttributesRepository.class);
|
||||
private AttributesRepository attributesRepository;
|
||||
|
||||
@Mock
|
||||
private final AttributeValuesRepository attributeValuesRepository = mock(AttributeValuesRepository.class);
|
||||
private AttributeValuesRepository attributeValuesRepository;
|
||||
|
||||
@Mock
|
||||
private final AttributesNoticeRepository attributesNoticeRepository = mock(AttributesNoticeRepository.class);
|
||||
private AttributesNoticeRepository attributesNoticeRepository;
|
||||
|
||||
@InjectMocks
|
||||
private NoticeService noticeService;
|
||||
@@ -52,7 +51,7 @@ class NoticeServiceTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Inicjalizacja danych testowych przed każdym testem");
|
||||
System.out.println("Przygotowanie danych testowych...");
|
||||
|
||||
sampleClient = new Client();
|
||||
sampleClient.setId(1L);
|
||||
@@ -78,69 +77,55 @@ class NoticeServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie wszystkich ogłoszeń - powinno zwrócić listę ogłoszeń")
|
||||
void getAllNotices_ShouldReturnListOfNotices() {
|
||||
System.out.println("Test: getAllNotices_ShouldReturnListOfNotices - powinien zwrócić listę ogłoszeń");
|
||||
|
||||
when(noticeRepository.findAll()).thenReturn(List.of(sampleNotice));
|
||||
|
||||
List<NoticeResponseDTO> result = noticeService.getAllNotices();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(sampleNotice.getIdNotice(), result.getFirst().getNoticeId());
|
||||
|
||||
System.out.println("Pomyślnie zwrócono listę ogłoszeń");
|
||||
System.out.println("Test pobrania wszystkich ogłoszeń zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie ogłoszenia po ID - gdy istnieje")
|
||||
void getNoticeById_WhenNoticeExists_ShouldReturnNotice() {
|
||||
System.out.println("Test: getNoticeById_WhenNoticeExists_ShouldReturnNotice - powinien zwrócić ogłoszenie gdy istnieje");
|
||||
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.of(sampleNotice));
|
||||
|
||||
NoticeResponseDTO result = noticeService.getNoticeById(1L);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(sampleNotice.getIdNotice(), result.getNoticeId());
|
||||
|
||||
System.out.println("Pomyślnie zwrócono istniejące ogłoszenie");
|
||||
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() {
|
||||
System.out.println("Test: getNoticeById_WhenNoticeNotExists_ShouldThrowException - powinien rzucić wyjątek gdy ogłoszenie nie istnieje");
|
||||
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(EntityNotFoundException.class, () -> noticeService.getNoticeById(1L));
|
||||
|
||||
System.out.println("Pomyślnie rzucono wyjątek dla nieistniejącego ogłoszenia");
|
||||
System.out.println("Test pobrania nieistniejącego ogłoszenia zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie nowego ogłoszenia - poprawne dane")
|
||||
void addNotice_WithValidData_ShouldCreateNotice() {
|
||||
System.out.println("Test: addNotice_WithValidData_ShouldCreateNotice - powinien utworzyć nowe ogłoszenie przy poprawnych danych");
|
||||
|
||||
when(clientRepository.findById(1L)).thenReturn(Optional.of(sampleClient));
|
||||
when(noticeRepository.save(any(Notice.class))).thenReturn(sampleNotice);
|
||||
|
||||
Long result = noticeService.addNotice(sampleNoticeRequest);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1L, result);
|
||||
|
||||
verify(noticeRepository, times(1)).save(any(Notice.class));
|
||||
|
||||
System.out.println("Pomyślnie utworzono nowe ogłoszenie");
|
||||
System.out.println("Test dodania ogłoszenia zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie ogłoszenia z atrybutami")
|
||||
void addNotice_WithAttributes_ShouldSaveAttributes() {
|
||||
System.out.println("Test: addNotice_WithAttributes_ShouldSaveAttributes - powinien zapisać atrybuty ogłoszenia");
|
||||
|
||||
AttributeDto attributeDto = new AttributeDto();
|
||||
attributeDto.setName("Materiał");
|
||||
attributeDto.setValue("Drewno");
|
||||
attributeDto.setName("Kolor");
|
||||
attributeDto.setValue("Zielony");
|
||||
sampleNoticeRequest.setAttributes(List.of(attributeDto));
|
||||
|
||||
when(clientRepository.findById(1L)).thenReturn(Optional.of(sampleClient));
|
||||
@@ -151,50 +136,39 @@ class NoticeServiceTest {
|
||||
Long result = noticeService.addNotice(sampleNoticeRequest);
|
||||
|
||||
assertNotNull(result);
|
||||
verify(attributesNoticeRepository, times(1)).save(any(AttributesNotice.class));
|
||||
|
||||
System.out.println("Pomyślnie zapisano atrybuty ogłoszenia");
|
||||
System.out.println("Test dodania ogłoszenia z atrybutami zakończony");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@DisplayName("Usunięcie istniejącego ogłoszenia")
|
||||
void deleteNotice_WhenNoticeExists_ShouldDeleteNotice() {
|
||||
System.out.println("Test: deleteNotice_WhenNoticeExists_ShouldDeleteNotice - powinien usunąć istniejące ogłoszenie");
|
||||
|
||||
when(noticeRepository.existsById(1L)).thenReturn(true);
|
||||
|
||||
noticeService.deleteNotice(1L);
|
||||
|
||||
verify(noticeRepository, times(1)).deleteById(1L);
|
||||
|
||||
System.out.println("Pomyślnie usunięto istniejące ogłoszenie");
|
||||
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() {
|
||||
System.out.println("Test: isNoticeOwnedByClient_WhenOwned_ShouldReturnTrue - powinien zwrócić true gdy ogłoszenie należy do klienta");
|
||||
|
||||
when(noticeRepository.existsByIdNoticeAndClientId(1L, 1L)).thenReturn(true);
|
||||
|
||||
boolean result = noticeService.isNoticeOwnedByClient(1L, 1L);
|
||||
|
||||
assertTrue(result);
|
||||
|
||||
System.out.println("Pomyślnie zwrócono true dla ogłoszenia należącego do klienta");
|
||||
System.out.println("Test sprawdzenia właściciela (true) zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Boostowanie ogłoszenia - aktualizacja daty publikacji")
|
||||
void boostNotice_ShouldUpdatePublishDate() {
|
||||
System.out.println("Test: boostNotice_ShouldUpdatePublishDate - powinien zaktualizować datę publikacji");
|
||||
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.of(sampleNotice));
|
||||
when(noticeRepository.save(any(Notice.class))).thenReturn(sampleNotice);
|
||||
|
||||
noticeService.boostNotice(1L);
|
||||
|
||||
assertNotNull(sampleNotice.getPublishDate());
|
||||
verify(noticeRepository, times(1)).save(sampleNotice);
|
||||
|
||||
System.out.println("Pomyślnie zaktualizowano datę publikacji ogłoszenia");
|
||||
System.out.println("Test boostowania ogłoszenia zakończony");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ 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;
|
||||
@@ -25,7 +26,10 @@ class ToolsTest {
|
||||
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;
|
||||
|
||||
@@ -35,6 +39,7 @@ class ToolsTest {
|
||||
Long result = tools.getClientIdFromRequest(request);
|
||||
|
||||
assertEquals(expectedClientId, result);
|
||||
}
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie pobrano ID klienta z tokenu");
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ 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;
|
||||
@@ -50,11 +51,15 @@ class WishlistControllerTest {
|
||||
|
||||
@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);
|
||||
|
||||
@@ -65,24 +70,34 @@ class WishlistControllerTest {
|
||||
|
||||
ResponseEntity<RequestResponseDTO> response = wishlistController.toggleWishlist(testNoticeId, request);
|
||||
|
||||
assertEquals(200, response.getStatusCodeValue());
|
||||
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.getStatusCodeValue());
|
||||
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);
|
||||
|
||||
@@ -93,15 +108,22 @@ class WishlistControllerTest {
|
||||
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ę");
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ 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;
|
||||
@@ -40,6 +41,8 @@ class WishlistServiceTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Przygotowanie danych testowych...");
|
||||
|
||||
testClient = new Client();
|
||||
testClient.setId(1L);
|
||||
testClient.setEmail("test@example.com");
|
||||
@@ -52,10 +55,15 @@ class WishlistServiceTest {
|
||||
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);
|
||||
|
||||
@@ -63,20 +71,30 @@ class WishlistServiceTest {
|
||||
|
||||
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);
|
||||
|
||||
@@ -87,15 +105,22 @@ class WishlistServiceTest {
|
||||
|
||||
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ę");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user