Skip to content
This repository has been archived by the owner on Dec 7, 2024. It is now read-only.

Commit

Permalink
feat(TEST): creating entities, DTO and services unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
alexZ7000 committed Oct 11, 2024
1 parent 02fec40 commit c1db925
Show file tree
Hide file tree
Showing 19 changed files with 1,112 additions and 33 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public Category toEntity() {
return category;
}

public static CategoryDTO toDTO(final CategoryDTO category) {
public static CategoryDTO toDTO(final Category category) {
final CategoryDTO categoryDTO = new CategoryDTO();
categoryDTO.setDescription(category.getDescription());
return categoryDTO;
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/example/comerce/core/dto/OrderDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ public Order toEntity() {
final Order order = new Order();
order.setDate(this.date);
order.setDiscount(this.discount);
order.setDiscount(this.total_price);
order.setTotal_price(this.total_price);
return order;
}

public static OrderDTO toDTO(final OrderDTO order) {
public static OrderDTO toDTO(Order order) {
final OrderDTO orderDTO = new OrderDTO();
orderDTO.setDate(order.getDate());
orderDTO.setDiscount(order.getDiscount());
orderDTO.setTotal_price(order.getDiscount());
orderDTO.setTotal_price(order.getTotal_price());
return orderDTO;
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/example/comerce/core/dto/ProductDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public Product toEntity() {
return product;
}

public static ProductDTO toDTO(final ProductDTO product) {
public static ProductDTO toDTO(final Product product) {
final ProductDTO productDTO = new ProductDTO();
productDTO.setName(product.getName());
productDTO.setStock_quantity(product.getStock_quantity());
Expand Down
21 changes: 14 additions & 7 deletions src/main/java/com/example/comerce/core/dto/UserDTO.java
Original file line number Diff line number Diff line change
@@ -1,39 +1,44 @@
package com.example.comerce.core.dto;

import com.example.comerce.core.entities.User;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import jakarta.validation.constraints.*;
import lombok.Getter;
import lombok.Setter;

import java.util.Collections;
import java.util.List;

@Getter
@Setter
public final class UserDTO {
@NotBlank(message = "Nome não pode estar em branco")
@Size(min = 3, max = 100, message = "Nome deve ter no mínimo 3 e no máximo 100 caracteres")
@Size(min = 3, max = 100, message = "Nome deve ter no mínimo 3 caracteres e no máximo 100 caracteres")
@Pattern(
regexp = "^\\p{L}[\\p{L}\\s]*$",
message = "Nome deve começar com uma letra, não pode conter números e pode incluir letras acentuadas e espaços."
)
private String name;

@NotBlank(message = "Telefone não pode estar em branco")
@Size(min = 11, max = 11, message = "Telefone deve ter 11 caracteres")
private String telephone;

@NotBlank(message = "CPF não pode estar em branco")
@Size(min = 11, max = 11, message = "CPF deve ter 11 caracteres")
private String cpf;

@NotBlank(message = "Email não pode estar em branco")
@Email(message = "E-mail inválido")
private String email;

@NotBlank(message = "Senha não pode estar em branco")
@Size(min = 6, max = 255, message = "Senha deve ter no mínimo 6 e no máximo 255 caracteres")
private String password;

@NotNull(message = "Endereço não pode ser null")
private AddressDTO address;

@NotNull(message = "Order não pode ser null")
private List<OrderDTO> orders;

public User toEntity() {
final User user = new User();
user.setName(this.name);
Expand All @@ -42,6 +47,7 @@ public User toEntity() {
user.setEmail(this.email);
user.setPassword(this.password);
user.setAddress(this.address.toEntity());
user.setOrders(this.orders.stream().map(OrderDTO::toEntity).toList());
return user;
}

Expand All @@ -52,6 +58,7 @@ public static UserDTO toDTO(User user) {
userDTO.setCpf(user.getCpf());
userDTO.setEmail(user.getEmail());
userDTO.setAddress(AddressDTO.toDTO(user.getAddress()));
userDTO.setOrders(user.getOrders().stream().map(OrderDTO::toDTO).toList());
return userDTO;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,12 @@ public void delete(final UUID categoryId) {
}

public Category update(final UUID categoryId, final Category category) {
category.setCategory_id(categoryId);
return categoryRepository.save(category);
final Category existingCategory = categoryRepository.findById(categoryId)
.orElseThrow(() -> new RuntimeException("Category Not Found"));

existingCategory.setDescription(category.getDescription());

return categoryRepository.save(existingCategory);
}

public Category findById(final UUID categoryId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.example.comerce.core.dto.OrderDTO;
import com.example.comerce.core.entities.Order;
import com.example.comerce.core.repository.OrderRepository;
import com.example.comerce.core.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

Expand Down Expand Up @@ -38,8 +39,13 @@ public void delete(final UUID orderId) {
}

public Order update(final UUID orderId, final OrderDTO orderDTO) {
final Order order = orderDTO.toEntity();
order.setOrder_id(orderId);
return orderRepository.save(order);
final Order existingOrder = orderRepository.findById(orderId)
.orElseThrow(() -> new RuntimeException("Order Not Found"));

existingOrder.setTotal_price(orderDTO.getTotal_price());
existingOrder.setDate(orderDTO.getDate());
existingOrder.setDiscount(orderDTO.getDiscount());

return orderRepository.save(existingOrder);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,17 @@ public void delete(final UUID productId) {
}

public Product update(final UUID productId, final ProductDTO productDTO) {
final Product product = productDTO.toEntity();
product.setProduct_id(productId);
return productRepository.save(product);
final Product existingProduct = productRepository.findById(productId)
.orElseThrow(() -> new RuntimeException("Product not found"));

existingProduct.setName(productDTO.getName());
existingProduct.setStock_quantity(productDTO.getStock_quantity());
existingProduct.setCost_price(productDTO.getCost_price());
existingProduct.setSell_price(productDTO.getSell_price());
existingProduct.setCreated_at(productDTO.getCreated_at());
existingProduct.setPrice(productDTO.getPrice());

return productRepository.save(existingProduct);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ public Optional<User> findById(final UUID userId) {

public User save(final UserDTO userDTO) {
final User user = userDTO.toEntity();
final String password = passwordEncoder.encode(user.getPassword());
user.setPassword(password);
final String encodedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
return userRepository.save(user);
}

Expand All @@ -56,15 +56,16 @@ public void delete(final UUID userId) {
}

public LoginResponse login(final String email, final String senha) throws Exception {
User user = userRepository.findByEmail(email).orElseThrow(() -> new Exception("User not found"));

final Authentication autenticacao = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(email, senha));

SecurityContextHolder.getContext().setAuthentication(autenticacao);
final String token = "Bearer " + jwtService.generateToken(email);

final User user = userRepository.findByEmail(email).orElseThrow(() -> new Exception("User not found"));

return new LoginResponse(token, user);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public SecurityFilterChain securityFilterChain(final HttpSecurity http) throws E
.requestMatchers("/api/users/login").permitAll()
.anyRequest().authenticated()
)
.addFilterBefore(new JWTAuthenticationFilter(jwtService, (CustomUserDetailsService) userDetailsService), UsernamePasswordAuthenticationFilter.class); // Adicionando o filtro
.addFilterBefore(new JWTAuthenticationFilter(jwtService, (CustomUserDetailsService) userDetailsService), UsernamePasswordAuthenticationFilter.class);

return http.build();
}
Expand Down
121 changes: 121 additions & 0 deletions src/test/java/com/example/comerce/core/entities/AddressTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package com.example.comerce.core.entities;

import com.example.comerce.core.dto.AddressDTO;
import com.example.comerce.shared.helpers.validators.entities.UUIDValidator;
import com.example.comerce.shared.helpers.validators.errors.ValidationUtil;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.Map;
import java.util.UUID;

import static org.junit.jupiter.api.Assertions.assertEquals;

final class AddressTest {
private final AddressDTO globalAddress = new AddressDTO();
private Validator validator;

@BeforeEach
public void setUp() {
final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();

globalAddress.setPostal_code("12345-678");
globalAddress.setStreet("Rua das Flores");
globalAddress.setNumber("100");
globalAddress.setNeighborhood("Centro");
globalAddress.setComplement("Apto 101");
globalAddress.setCity("São Paulo");
globalAddress.setState("SP");
}

@Test
public void testAddress() {
final Address address = new Address();

final UUID addressId = UUID.randomUUID();
address.setAddress_id(addressId);
address.setPostal_code("12345-678");
address.setStreet("Rua das Flores");
address.setNumber("100");
address.setNeighborhood("Centro");
address.setComplement("Apto 101");
address.setCity("São Paulo");
address.setState("SP");

assertEquals(addressId, address.getAddress_id());
assertEquals("12345-678", address.getPostal_code());
assertEquals("Rua das Flores", address.getStreet());
assertEquals("100", address.getNumber());
assertEquals("Centro", address.getNeighborhood());
assertEquals("Apto 101", address.getComplement());
assertEquals("São Paulo", address.getCity());
assertEquals("SP", address.getState());
}

@Test
public void testInvalidAddressId() {
final String addressId = !UUIDValidator.validateUUID("addressId", "123e4567-e89b-12d3-a456-42661417400")
? "UUID inválido" : "UUID válido";
assertEquals("UUID inválido", addressId);
}

@Test
public void testInvalidPostalCode() {
// Teste 1: CEP em branco
globalAddress.setPostal_code("");
Map<String, String> violationMessages = ValidationUtil.validateAndGetViolations(validator, globalAddress);
assertEquals("CEP não pode estar em branco", violationMessages.get("postal_code"));
}

@Test
public void testInvalidStreet() {
// Teste 1: Rua em branco
globalAddress.setStreet("");
Map<String, String> violationMessages = ValidationUtil.validateAndGetViolations(validator, globalAddress);
assertEquals("Rua não pode estar em branco", violationMessages.get("street"));
}

@Test
public void testInvalidNumber() {
// Teste 1: Número em branco
globalAddress.setNumber("");
Map<String, String> violationMessages = ValidationUtil.validateAndGetViolations(validator, globalAddress);
assertEquals("Número não pode estar em branco", violationMessages.get("number"));
}

@Test
public void testInvalidNeighborhood() {
// Teste 1: Bairro em branco
globalAddress.setNeighborhood("");
Map<String, String> violationMessages = ValidationUtil.validateAndGetViolations(validator, globalAddress);
assertEquals("Bairro não pode estar em branco", violationMessages.get("neighborhood"));
}

@Test
public void testInvalidComplement() {
// Teste 1: Complemento em branco
globalAddress.setComplement("");
Map<String, String> violationMessages = ValidationUtil.validateAndGetViolations(validator, globalAddress);
assertEquals("Complemento não pode estar em branco", violationMessages.get("complement"));
}

@Test
public void testInvalidCity() {
// Teste 1: Cidade em branco
globalAddress.setCity("");
Map<String, String> violationMessages = ValidationUtil.validateAndGetViolations(validator, globalAddress);
assertEquals("Cidade não pode estar em branco", violationMessages.get("city"));
}

@Test
public void testInvalidState() {
// Teste 1: Estado em branco
globalAddress.setState("");
Map<String, String> violationMessages = ValidationUtil.validateAndGetViolations(validator, globalAddress);
assertEquals("Estado não pode estar em branco", violationMessages.get("state"));
}
}
Loading

0 comments on commit c1db925

Please sign in to comment.