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

Commit

Permalink
feat(Tests): creating integration tests, and improving unit tests per…
Browse files Browse the repository at this point in the history
…formance
  • Loading branch information
alexZ7000 committed Oct 14, 2024
1 parent 58cd0fa commit b093b15
Show file tree
Hide file tree
Showing 12 changed files with 178 additions and 16 deletions.
7 changes: 6 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,12 @@
<version>13.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>

<build>
<plugins>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ final class AddressTest {

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

globalAddress.setPostal_code("12345-678");
globalAddress.setStreet("Rua das Flores");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ final class CategoryTest {

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

globalCategory.setDescription("Eletrônicos e Gadgets");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ final class OrderTest {

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

globalOrder.setDate(new Date());
globalOrder.setDiscount(100.00);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ final class ProductTest {

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

globalProduct.setName("Laptop");
globalProduct.setStock_quantity(10);
Expand Down
5 changes: 3 additions & 2 deletions src/test/java/com/example/comerce/core/entities/UserTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ final class UserTest {

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

globalUser.setName("Alessandro Lima");
globalUser.setEmail("alessandro@email.com");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.example.comerce.core.dto.CategoryDTO;
import com.example.comerce.core.entities.Category;
import com.example.comerce.core.repository.CategoryRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
Expand All @@ -27,16 +28,30 @@ final class CategoryServiceTest {
private Category category = new Category();
private final UUID categoryId = UUID.randomUUID();

private AutoCloseable closeable;

@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
closeable = MockitoAnnotations.openMocks(this);

categoryDTO.setDescription("Category description");

category = categoryDTO.toEntity();
category.setCategory_id(categoryId);
}

@AfterEach
public void tearDown() {
if (closeable != null) {
try {
closeable.close();
}
catch (Exception e) {
System.err.println("Erro ao fechar os recursos: " + e.getMessage());
}
}
}

@Test
public void testFindById_Success() {
when(categoryRepository.findById(categoryId)).thenReturn(Optional.of(category));
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 org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
Expand Down Expand Up @@ -30,9 +31,11 @@ final class OrderServiceTest {
private Order order = new Order();
private final UUID orderId = UUID.randomUUID();

private AutoCloseable closeable;

@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
closeable = MockitoAnnotations.openMocks(this);

orderDTO.setDate(new Date());
orderDTO.setDiscount(100.00);
Expand All @@ -42,6 +45,18 @@ public void setUp() {
order.setOrder_id(orderId);
}

@AfterEach
public void tearDown() {
if (closeable != null) {
try {
closeable.close();
}
catch (Exception e) {
System.err.println("Erro ao fechar os recursos: " + e.getMessage());
}
}
}

@Test
public void testFindById_Success() {
when(orderService.findById(orderId)).thenReturn(Optional.of(order));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.example.comerce.core.dto.ProductDTO;
import com.example.comerce.core.entities.Product;
import com.example.comerce.core.repository.ProductRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
Expand Down Expand Up @@ -30,9 +31,11 @@ final class ProductServiceTest {
private Product product = new Product();
private final UUID productId = UUID.randomUUID();

private AutoCloseable closeable;

@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
closeable = MockitoAnnotations.openMocks(this);

productDTO.setName("Laptop");
productDTO.setStock_quantity(10);
Expand All @@ -45,6 +48,11 @@ public void setUp() {
product.setProduct_id(productId);
}

@AfterEach
public void tearDown() throws Exception {
if (closeable != null) closeable.close();
}

@Test
public void testFindById_Success() {
when(productRepository.findById(productId)).thenReturn(Optional.of(product));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.example.comerce.core.entities.User;
import com.example.comerce.core.repository.UserRepository;
import com.example.comerce.shared.security.JWTService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
Expand Down Expand Up @@ -47,9 +48,11 @@ final class UserServiceTest {
private User user;
private UUID userId;

private AutoCloseable closeable;

@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
closeable = MockitoAnnotations.openMocks(this);

userId = UUID.randomUUID();
userDTO = new UserDTO();
Expand Down Expand Up @@ -79,6 +82,18 @@ public void setUp() {
user.setUser_id(userId);
}

@AfterEach
public void tearDown() {
if (closeable != null) {
try {
closeable.close();
}
catch (Exception e) {
System.err.println("Erro ao fechar os recursos: " + e.getMessage());
}
}
}

@Test
public void testFindById_Success() {
when(userRepository.findById(userId)).thenReturn(Optional.of(user));
Expand All @@ -100,13 +115,18 @@ public void testFindById_UserNotFound() {

@Test
public void testSaveUser() {
// Não testa a senha, pois a senha é criptografada no método save
String encodedPassword = "encodedPassword123";
when(passwordEncoder.encode(userDTO.getPassword())).thenReturn(encodedPassword);

user.setPassword(encodedPassword);
when(userRepository.save(any(User.class))).thenReturn(user);

User savedUser = userService.save(userDTO);

assertNotNull(savedUser, "Não é possível salvar dados vazios");
assertEquals(user.getUser_id(), savedUser.getUser_id());
assertEquals(encodedPassword, savedUser.getPassword(), "A senha não foi codificada corretamente");
verify(passwordEncoder).encode(userDTO.getPassword());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.example.comerce.integration.repository;

import com.example.comerce.core.entities.User;
import com.example.comerce.core.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

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

@DataJpaTest
@Transactional
public class UserRepositoryIntegrationTest {

@Autowired
private UserRepository userRepository;

@Test
public void testSaveAndFindUser() {
User user = new User();
user.setName("Alessandro Lima");
user.setEmail("alessandro@email.com");
user.setCpf("12345678901");
user.setTelephone("12345678901");
user.setPassword("senha123");

User savedUser = userRepository.save(user);
assertNotNull(savedUser.getUser_id());

Optional<User> foundUser = userRepository.findById(savedUser.getUser_id());
assertTrue(foundUser.isPresent());
assertEquals(user.getName(), foundUser.get().getName());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.example.comerce.integration.services;

import com.example.comerce.core.entities.User;
import com.example.comerce.core.repository.UserRepository;
import com.example.comerce.core.services.UserService;
import org.junit.jupiter.api.BeforeEach;
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.transaction.annotation.Transactional;

import java.util.Optional;
import java.util.UUID;

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

@SpringBootTest
@AutoConfigureMockMvc
@Transactional // Garante que cada teste seja executado em uma transação que será revertida
public class UserServiceIntegrationTest {

@Autowired
private UserService userService;

@Autowired
private UserRepository userRepository;

private UUID userId;

@BeforeEach
public void setUp() {
User user = new User();
user.setName("Alessandro Lima");
user.setEmail("alessandro@email.com");
user.setCpf("12345678901");
user.setTelephone("12345678901");
user.setPassword("senha123");
userId = userRepository.save(user).getUser_id();
}

@Test
public void testFindById() {
Optional<User> foundUser = userService.findById(userId);

assertTrue(foundUser.isPresent());
assertEquals(userId, foundUser.get().getUser_id());
}

@Test
public void testDeleteUser() {
userService.delete(userId);
Optional<User> foundUser = userService.findById(userId);

assertFalse(foundUser.isPresent());
}
}

0 comments on commit b093b15

Please sign in to comment.