Skip to content

Commit fe72380

Browse files
committed
added tests for persistence classes (#27)
1 parent b1f5001 commit fe72380

File tree

9 files changed

+721
-12
lines changed

9 files changed

+721
-12
lines changed

.github/workflows/build_mvn.yml

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name: Echo Secrets and Build JavaFX Project
1+
name: Build, Test, and Validate with PostgreSQL
22

33
on:
44
push:
@@ -9,8 +9,15 @@ jobs:
99
build:
1010
runs-on: ubuntu-latest
1111

12-
env:
13-
MY_VARIABLE: "This is my public variable" # Variável de ambiente pública
12+
services:
13+
postgres:
14+
image: postgres:15 # Versão do PostgreSQL
15+
ports:
16+
- 5432:5432 # Porta padrão do PostgreSQL
17+
env:
18+
POSTGRES_USER: postgres # Usuário do banco
19+
POSTGRES_PASSWORD: password # Senha do banco
20+
POSTGRES_DB: mundoanimal # Banco de dados usado nos testes
1421

1522
steps:
1623
- name: Checkout code
@@ -25,14 +32,14 @@ jobs:
2532
- name: Setup Maven
2633
run: mvn -version # Verifica a versão do Maven
2734

28-
- name: Echo environment variable
29-
run: echo "My environment variable is $MY_VARIABLE" # Exibe a variável pública
30-
31-
- name: Echo GitHub secret
32-
run: echo "My GitHub secret is ${{ secrets.MY_GITHUB_SECRET }}" # Exibe o valor da chave secreta
35+
- name: Configure persistence.xml for tests
36+
run: |
37+
sed -i 's|<property name="jakarta.persistence.jdbc.url" value=".*"/>|<property name="jakarta.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/mundoanimal"/>|' src/main/resources/META-INF/persistence.xml
38+
sed -i 's|<property name="jakarta.persistence.jdbc.user" value=".*"/>|<property name="jakarta.persistence.jdbc.user" value="postgres"/>|' src/main/resources/META-INF/persistence.xml
39+
sed -i 's|<property name="jakarta.persistence.jdbc.password" value=".*"/>|<property name="jakarta.persistence.jdbc.password" value="password"/>|' src/main/resources/META-INF/persistence.xml
3340
3441
- name: Run Tests
3542
run: mvn test
3643

3744
- name: Build with Maven
38-
run: mvn clean package # Compila o projeto
45+
run: mvn clean package # Compila o projeto

pom.xml

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,10 +100,39 @@
100100
<version>1.3.0</version>
101101
</dependency>
102102

103+
<!-- JUnit 5 -->
104+
<dependency>
105+
<groupId>org.junit.jupiter</groupId>
106+
<artifactId>junit-jupiter</artifactId>
107+
<version>5.10.0</version>
108+
<scope>test</scope>
109+
</dependency>
110+
111+
<!-- Mockito -->
112+
<dependency>
113+
<groupId>org.mockito</groupId>
114+
<artifactId>mockito-core</artifactId>
115+
<version>5.5.0</version>
116+
<scope>test</scope>
117+
</dependency>
118+
119+
<!-- H2 Database for testing repository -->
120+
<dependency>
121+
<groupId>com.h2database</groupId>
122+
<artifactId>h2</artifactId>
123+
<version>2.3.232</version>
124+
<scope>test</scope>
125+
</dependency>
126+
103127
</dependencies>
104128

105129
<build>
106130
<plugins>
131+
<plugin>
132+
<groupId>org.apache.maven.plugins</groupId>
133+
<artifactId>maven-surefire-plugin</artifactId>
134+
<version>3.5.2</version>
135+
</plugin>
107136
<plugin>
108137
<groupId>org.apache.maven.plugins</groupId>
109138
<artifactId>maven-jar-plugin</artifactId>

src/main/java/com/carvalhotechsolutions/mundoanimal/controllers/modals/ModalCriarAgendamentoController.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
import java.net.URL;
2121
import java.time.LocalDate;
22+
import java.time.LocalDateTime;
2223
import java.time.LocalTime;
2324
import java.time.format.DateTimeFormatter;
2425
import java.util.ArrayList;
@@ -181,15 +182,22 @@ private List<String> gerarHorariosDisponiveis(LocalDate data, List<Agendamento>
181182
LocalTime inicio = LocalTime.of(6, 0);
182183
LocalTime fim = LocalTime.of(20, 0);
183184

185+
// Obter a data e hora atual
186+
LocalDateTime agora = LocalDateTime.now();
187+
184188
while (inicio.isBefore(fim.plusMinutes(1))) {
185189
String horarioStr = inicio.format(DateTimeFormatter.ofPattern("HH:mm"));
190+
LocalTime finalInicio = inicio;
186191

187192
// Verificar se o horário já está ocupado
188-
LocalTime finalInicio = inicio;
189193
boolean horarioOcupado = agendamentosExistentes.stream()
190194
.anyMatch(a -> a.getHorarioAgendamento().equals(finalInicio));
191195

192-
if (!horarioOcupado) {
196+
// Verificar se o horário já passou (apenas para a data atual)
197+
boolean horarioPassou = data.equals(agora.toLocalDate()) && inicio.isBefore(agora.toLocalTime());
198+
199+
// Adicionar horário apenas se não estiver ocupado e não tiver passado
200+
if (!horarioOcupado && !horarioPassou) {
193201
horariosDisponiveis.add(horarioStr);
194202
}
195203

src/main/resources/META-INF/persistence.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
<property name="hibernate.show_sql" value="true" />
2121
<property name="hibernate.format_sql" value="true" />
22-
<property name="hibernate.hbm2ddl.auto" value="update" />
22+
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
2323
<!-- Deixei a propriedade DDL auto como create-drop para facilitar
2424
os testes no banco de dados, fica ao critério de cada um do @Back
2525
<property name="hibernate.hbm2ddl.auto" value="update" /> -->
Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
package com.carvalhotechsolutions.mundoanimal.repositories;
2+
3+
import com.carvalhotechsolutions.mundoanimal.database.JPAutil;
4+
import com.carvalhotechsolutions.mundoanimal.enums.EspecieAnimal;
5+
import com.carvalhotechsolutions.mundoanimal.model.Agendamento;
6+
import com.carvalhotechsolutions.mundoanimal.model.Animal;
7+
import com.carvalhotechsolutions.mundoanimal.model.Cliente;
8+
import com.carvalhotechsolutions.mundoanimal.model.Servico;
9+
import jakarta.persistence.EntityManager;
10+
import jakarta.persistence.NoResultException;
11+
import org.junit.jupiter.api.BeforeEach;
12+
import org.junit.jupiter.api.Test;
13+
14+
import java.math.BigDecimal;
15+
import java.time.LocalDate;
16+
import java.time.LocalTime;
17+
import java.util.List;
18+
import java.util.Random;
19+
20+
import static org.junit.jupiter.api.Assertions.*;
21+
22+
public class AgendamentoRepositoryTest {
23+
24+
private AgendamentoRepository agendamentoRepository = new AgendamentoRepository();
25+
private EntityManager em;
26+
27+
@BeforeEach
28+
void setUp() {
29+
em = JPAutil.getEntityManager();
30+
limparBaseDeDados();
31+
}
32+
33+
@Test
34+
void save() {
35+
// Arrange
36+
Agendamento agendamento = criarAgendamentoCompleto();
37+
38+
// Act
39+
Agendamento savedAgendamento = agendamentoRepository.save(agendamento);
40+
41+
// Assert
42+
assertNotNull(savedAgendamento.getId());
43+
assertEquals(agendamento.getDataAgendamento(), savedAgendamento.getDataAgendamento());
44+
assertEquals(agendamento.getHorarioAgendamento(), savedAgendamento.getHorarioAgendamento());
45+
}
46+
47+
@Test
48+
void update() {
49+
// Arrange
50+
Agendamento agendamento = criarAgendamentoCompleto();
51+
Agendamento savedAgendamento = agendamentoRepository.save(agendamento);
52+
53+
LocalTime novoHorario = LocalTime.of(15, 0);
54+
savedAgendamento.setHorarioAgendamento(novoHorario);
55+
56+
// Act
57+
Agendamento updatedAgendamento = agendamentoRepository.save(savedAgendamento);
58+
59+
// Assert
60+
assertEquals(novoHorario, updatedAgendamento.getHorarioAgendamento());
61+
assertEquals(savedAgendamento.getId(), updatedAgendamento.getId());
62+
}
63+
64+
@Test
65+
void findById() {
66+
// Arrange
67+
Agendamento agendamento = criarAgendamentoCompleto();
68+
Agendamento savedAgendamento = agendamentoRepository.save(agendamento);
69+
70+
// Act
71+
Agendamento foundAgendamento = agendamentoRepository.findById(savedAgendamento.getId());
72+
73+
// Assert
74+
assertNotNull(foundAgendamento);
75+
assertEquals(savedAgendamento.getId(), foundAgendamento.getId());
76+
}
77+
78+
@Test
79+
void findAll() {
80+
// Arrange
81+
Agendamento agendamento1 = criarAgendamento(LocalDate.now(), LocalTime.of(14, 0));
82+
Agendamento agendamento2 = criarAgendamento(LocalDate.now(), LocalTime.of(9, 0));
83+
Agendamento agendamento3 = criarAgendamento(LocalDate.now().plusDays(1), LocalTime.of(10, 0));
84+
85+
agendamentoRepository.save(agendamento1);
86+
agendamentoRepository.save(agendamento2);
87+
agendamentoRepository.save(agendamento3);
88+
89+
// Act
90+
List<Agendamento> agendamentos = agendamentoRepository.findAll();
91+
92+
// Assert
93+
assertEquals(3, agendamentos.size());
94+
assertTrue(agendamentos.get(0).getHorarioAgendamento().isBefore(agendamentos.get(1).getHorarioAgendamento()));
95+
assertTrue(agendamentos.get(0).getDataAgendamento().isBefore(agendamentos.get(2).getDataAgendamento()) ||
96+
agendamentos.get(0).getDataAgendamento().isEqual(agendamentos.get(2).getDataAgendamento()));
97+
}
98+
99+
@Test
100+
void deleteById() {
101+
// Arrange
102+
Agendamento agendamento = criarAgendamentoCompleto();
103+
Agendamento savedAgendamento = agendamentoRepository.save(agendamento);
104+
105+
// Act
106+
agendamentoRepository.deleteById(savedAgendamento.getId());
107+
108+
// Assert
109+
assertThrows(NoResultException.class, () -> {
110+
agendamentoRepository.findById(savedAgendamento.getId());
111+
});
112+
}
113+
114+
@Test
115+
void verificarDisponibilidadeHorario() {
116+
// Arrange
117+
LocalDate data = LocalDate.now();
118+
LocalTime horario = LocalTime.of(14, 0);
119+
Agendamento agendamento = criarAgendamento(data, horario);
120+
agendamentoRepository.save(agendamento);
121+
122+
// Act & Assert
123+
assertFalse(agendamentoRepository.verificarDisponibilidadeHorario(data, horario));
124+
assertTrue(agendamentoRepository.verificarDisponibilidadeHorario(data, horario.plusHours(1)));
125+
}
126+
127+
@Test
128+
void buscarAgendamentosPorData() {
129+
// Arrange
130+
LocalDate hoje = LocalDate.now();
131+
LocalDate amanha = hoje.plusDays(1);
132+
133+
Agendamento agendamento1 = criarAgendamento(hoje, LocalTime.of(9, 0));
134+
Agendamento agendamento2 = criarAgendamento(hoje, LocalTime.of(14, 0));
135+
Agendamento agendamento3 = criarAgendamento(amanha, LocalTime.of(10, 0));
136+
137+
agendamentoRepository.save(agendamento1);
138+
agendamentoRepository.save(agendamento2);
139+
agendamentoRepository.save(agendamento3);
140+
141+
// Act
142+
List<Agendamento> agendamentosHoje = agendamentoRepository.buscarAgendamentosPorData(hoje);
143+
List<Agendamento> agendamentosAmanha = agendamentoRepository.buscarAgendamentosPorData(amanha);
144+
145+
// Assert
146+
assertEquals(2, agendamentosHoje.size());
147+
assertEquals(1, agendamentosAmanha.size());
148+
}
149+
150+
private Agendamento criarAgendamentoCompleto() {
151+
Cliente cliente = new Cliente();
152+
cliente.setNome("Cliente Teste " + System.nanoTime());
153+
cliente.setTelefone(gerarNumero11Digitos());
154+
155+
Animal animal = new Animal();
156+
animal.setNome("Pet Teste");
157+
animal.setEspecie(EspecieAnimal.CACHORRO);
158+
animal.setDono(cliente);
159+
160+
Servico servico = new Servico();
161+
servico.setNomeServico("Banho");
162+
servico.setDescricao("Banho completo");
163+
servico.setValorServico(BigDecimal.valueOf(50.0));
164+
165+
em.getTransaction().begin();
166+
em.persist(cliente);
167+
em.persist(animal);
168+
em.persist(servico);
169+
em.getTransaction().commit();
170+
171+
Agendamento agendamento = new Agendamento();
172+
agendamento.setCliente(cliente);
173+
agendamento.setAnimal(animal);
174+
agendamento.setServico(servico);
175+
agendamento.setDataAgendamento(LocalDate.now());
176+
agendamento.setHorarioAgendamento(LocalTime.of(14, 0));
177+
agendamento.setResponsavelAtendimento("Funcionário Teste");
178+
179+
return agendamento;
180+
}
181+
182+
private Agendamento criarAgendamento(LocalDate data, LocalTime horario) {
183+
Agendamento agendamento = criarAgendamentoCompleto();
184+
agendamento.setDataAgendamento(data);
185+
agendamento.setHorarioAgendamento(horario);
186+
return agendamento;
187+
}
188+
189+
private void limparBaseDeDados() {
190+
em.getTransaction().begin();
191+
em.createQuery("DELETE FROM Agendamento").executeUpdate();
192+
em.createQuery("DELETE FROM Animal").executeUpdate();
193+
em.createQuery("DELETE FROM Cliente").executeUpdate();
194+
em.createQuery("DELETE FROM Servico").executeUpdate();
195+
em.getTransaction().commit();
196+
}
197+
198+
private String gerarNumero11Digitos() {
199+
Random random = new Random();
200+
201+
// Gera um número entre 10000000000L e 99999999999L (11 dígitos)
202+
long minimo = 10000000000L;
203+
long maximo = 99999999999L;
204+
205+
// Calcula um número aleatório dentro do intervalo
206+
long numeroAleatorio = minimo + ((long)(random.nextDouble() * (maximo - minimo)));
207+
208+
return String.valueOf(numeroAleatorio);
209+
}
210+
}

0 commit comments

Comments
 (0)