Authentification stable - WIP

This commit is contained in:
DahoudG
2025-09-19 12:35:46 +00:00
parent 63fe107f98
commit 098894bdc1
383 changed files with 13072 additions and 93334 deletions

View File

@@ -1,150 +0,0 @@
package dev.lions.unionflow.server;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests pour UnionFlowServerApplication
*
* @author Lions Dev Team
* @since 2025-01-10
*/
@QuarkusTest
@DisplayName("Tests UnionFlowServerApplication")
class UnionFlowServerApplicationTest {
@Test
@DisplayName("Test de l'application - Contexte Quarkus")
void testApplicationContext() {
// Given & When & Then
// Le simple fait que ce test s'exécute sans erreur
// prouve que l'application Quarkus démarre correctement
assertThat(true).isTrue();
}
@Test
@DisplayName("Test de l'application - Classe principale existe")
void testMainClassExists() {
// Given & When & Then
assertThat(UnionFlowServerApplication.class).isNotNull();
assertThat(UnionFlowServerApplication.class.getAnnotation(io.quarkus.runtime.annotations.QuarkusMain.class))
.isNotNull();
}
@Test
@DisplayName("Test de l'application - Implémente QuarkusApplication")
void testImplementsQuarkusApplication() {
// Given & When & Then
assertThat(io.quarkus.runtime.QuarkusApplication.class)
.isAssignableFrom(UnionFlowServerApplication.class);
}
@Test
@DisplayName("Test de l'application - Méthode main existe")
void testMainMethodExists() throws NoSuchMethodException {
// Given & When & Then
assertThat(UnionFlowServerApplication.class.getMethod("main", String[].class))
.isNotNull();
}
@Test
@DisplayName("Test de l'application - Méthode run existe")
void testRunMethodExists() throws NoSuchMethodException {
// Given & When & Then
assertThat(UnionFlowServerApplication.class.getMethod("run", String[].class))
.isNotNull();
}
@Test
@DisplayName("Test de l'application - Annotation ApplicationScoped")
void testApplicationScopedAnnotation() {
// Given & When & Then
assertThat(UnionFlowServerApplication.class.getAnnotation(jakarta.enterprise.context.ApplicationScoped.class))
.isNotNull();
}
@Test
@DisplayName("Test de l'application - Logger statique")
void testStaticLogger() throws NoSuchFieldException {
// Given & When & Then
assertThat(UnionFlowServerApplication.class.getDeclaredField("LOG"))
.isNotNull();
}
@Test
@DisplayName("Test de l'application - Instance créable")
void testInstanceCreation() {
// Given & When
UnionFlowServerApplication app = new UnionFlowServerApplication();
// Then
assertThat(app).isNotNull();
assertThat(app).isInstanceOf(io.quarkus.runtime.QuarkusApplication.class);
}
@Test
@DisplayName("Test de la méthode main - Signature correcte")
void testMainMethodSignature() throws NoSuchMethodException {
// Given & When
var mainMethod = UnionFlowServerApplication.class.getMethod("main", String[].class);
// Then
assertThat(mainMethod.getReturnType()).isEqualTo(void.class);
assertThat(java.lang.reflect.Modifier.isStatic(mainMethod.getModifiers())).isTrue();
assertThat(java.lang.reflect.Modifier.isPublic(mainMethod.getModifiers())).isTrue();
}
@Test
@DisplayName("Test de la méthode run - Signature correcte")
void testRunMethodSignature() throws NoSuchMethodException {
// Given & When
var runMethod = UnionFlowServerApplication.class.getMethod("run", String[].class);
// Then
assertThat(runMethod.getReturnType()).isEqualTo(int.class);
assertThat(java.lang.reflect.Modifier.isPublic(runMethod.getModifiers())).isTrue();
assertThat(runMethod.getExceptionTypes()).contains(Exception.class);
}
@Test
@DisplayName("Test de l'implémentation QuarkusApplication")
void testQuarkusApplicationImplementation() {
// Given & When & Then
assertThat(io.quarkus.runtime.QuarkusApplication.class.isAssignableFrom(UnionFlowServerApplication.class))
.isTrue();
}
@Test
@DisplayName("Test du package de la classe")
void testPackageName() {
// Given & When & Then
assertThat(UnionFlowServerApplication.class.getPackage().getName())
.isEqualTo("dev.lions.unionflow.server");
}
@Test
@DisplayName("Test de la classe - Modificateurs")
void testClassModifiers() {
// Given & When & Then
assertThat(java.lang.reflect.Modifier.isPublic(UnionFlowServerApplication.class.getModifiers())).isTrue();
assertThat(java.lang.reflect.Modifier.isFinal(UnionFlowServerApplication.class.getModifiers())).isFalse();
assertThat(java.lang.reflect.Modifier.isAbstract(UnionFlowServerApplication.class.getModifiers())).isFalse();
}
@Test
@DisplayName("Test des constructeurs")
void testConstructors() {
// Given & When
var constructors = UnionFlowServerApplication.class.getConstructors();
// Then
assertThat(constructors).hasSize(1);
assertThat(constructors[0].getParameterCount()).isEqualTo(0);
assertThat(java.lang.reflect.Modifier.isPublic(constructors[0].getModifiers())).isTrue();
}
}

View File

@@ -1,243 +0,0 @@
package dev.lions.unionflow.server.entity;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests simples pour l'entité Membre
*
* @author Lions Dev Team
* @since 2025-01-10
*/
@DisplayName("Tests simples Membre")
class MembreSimpleTest {
@Test
@DisplayName("Test de création d'un membre avec builder")
void testCreationMembreAvecBuilder() {
// Given & When
Membre membre = Membre.builder()
.numeroMembre("UF2025-TEST01")
.prenom("Jean")
.nom("Dupont")
.email("jean.dupont@test.com")
.telephone("221701234567")
.dateNaissance(LocalDate.of(1990, 5, 15))
.dateAdhesion(LocalDate.now())
.actif(true)
.build();
// Then
assertThat(membre).isNotNull();
assertThat(membre.getNumeroMembre()).isEqualTo("UF2025-TEST01");
assertThat(membre.getPrenom()).isEqualTo("Jean");
assertThat(membre.getNom()).isEqualTo("Dupont");
assertThat(membre.getEmail()).isEqualTo("jean.dupont@test.com");
assertThat(membre.getTelephone()).isEqualTo("221701234567");
assertThat(membre.getDateNaissance()).isEqualTo(LocalDate.of(1990, 5, 15));
assertThat(membre.getActif()).isTrue();
}
@Test
@DisplayName("Test de la méthode getNomComplet")
void testGetNomComplet() {
// Given
Membre membre = Membre.builder()
.prenom("Jean")
.nom("Dupont")
.build();
// When
String nomComplet = membre.getNomComplet();
// Then
assertThat(nomComplet).isEqualTo("Jean Dupont");
}
@Test
@DisplayName("Test de la méthode isMajeur - Majeur")
void testIsMajeurMajeur() {
// Given
Membre membre = Membre.builder()
.dateNaissance(LocalDate.of(1990, 5, 15))
.build();
// When
boolean majeur = membre.isMajeur();
// Then
assertThat(majeur).isTrue();
}
@Test
@DisplayName("Test de la méthode isMajeur - Mineur")
void testIsMajeurMineur() {
// Given
Membre membre = Membre.builder()
.dateNaissance(LocalDate.now().minusYears(17))
.build();
// When
boolean majeur = membre.isMajeur();
// Then
assertThat(majeur).isFalse();
}
@Test
@DisplayName("Test de la méthode getAge")
void testGetAge() {
// Given
Membre membre = Membre.builder()
.dateNaissance(LocalDate.now().minusYears(25))
.build();
// When
int age = membre.getAge();
// Then
assertThat(age).isEqualTo(25);
}
@Test
@DisplayName("Test de création d'un membre sans builder")
void testCreationMembreSansBuilder() {
// Given & When
Membre membre = new Membre();
membre.setNumeroMembre("UF2025-TEST02");
membre.setPrenom("Marie");
membre.setNom("Martin");
membre.setEmail("marie.martin@test.com");
membre.setActif(true);
// Then
assertThat(membre).isNotNull();
assertThat(membre.getNumeroMembre()).isEqualTo("UF2025-TEST02");
assertThat(membre.getPrenom()).isEqualTo("Marie");
assertThat(membre.getNom()).isEqualTo("Martin");
assertThat(membre.getEmail()).isEqualTo("marie.martin@test.com");
assertThat(membre.getActif()).isTrue();
}
@Test
@DisplayName("Test des annotations JPA")
void testAnnotationsJPA() {
// Given & When & Then
assertThat(Membre.class.getAnnotation(jakarta.persistence.Entity.class)).isNotNull();
assertThat(Membre.class.getAnnotation(jakarta.persistence.Table.class)).isNotNull();
assertThat(Membre.class.getAnnotation(jakarta.persistence.Table.class).name()).isEqualTo("membres");
}
@Test
@DisplayName("Test des annotations Lombok")
void testAnnotationsLombok() {
// Given & When & Then
// Vérifier que les annotations Lombok sont présentes (peuvent être null selon la compilation)
// Nous testons plutôt que les méthodes générées existent
assertThat(Membre.builder()).isNotNull();
Membre membre = new Membre();
assertThat(membre.toString()).isNotNull();
assertThat(membre.hashCode()).isNotZero();
}
@Test
@DisplayName("Test de l'héritage PanacheEntity")
void testHeritageePanacheEntity() {
// Given & When & Then
assertThat(io.quarkus.hibernate.orm.panache.PanacheEntity.class)
.isAssignableFrom(Membre.class);
}
@Test
@DisplayName("Test des méthodes héritées de PanacheEntity")
void testMethodesHeriteesPanacheEntity() throws NoSuchMethodException {
// Given & When & Then
// Vérifier que les méthodes de PanacheEntity sont disponibles
assertThat(Membre.class.getMethod("persist")).isNotNull();
assertThat(Membre.class.getMethod("delete")).isNotNull();
assertThat(Membre.class.getMethod("isPersistent")).isNotNull();
}
@Test
@DisplayName("Test de toString")
void testToString() {
// Given
Membre membre = Membre.builder()
.numeroMembre("UF2025-TEST01")
.prenom("Jean")
.nom("Dupont")
.email("jean.dupont@test.com")
.actif(true)
.build();
// When
String toString = membre.toString();
// Then
assertThat(toString).isNotNull();
assertThat(toString).contains("Jean");
assertThat(toString).contains("Dupont");
assertThat(toString).contains("UF2025-TEST01");
assertThat(toString).contains("jean.dupont@test.com");
}
@Test
@DisplayName("Test de hashCode")
void testHashCode() {
// Given
Membre membre1 = Membre.builder()
.numeroMembre("UF2025-TEST01")
.prenom("Jean")
.nom("Dupont")
.email("jean.dupont@test.com")
.build();
Membre membre2 = Membre.builder()
.numeroMembre("UF2025-TEST01")
.prenom("Jean")
.nom("Dupont")
.email("jean.dupont@test.com")
.build();
// When & Then
assertThat(membre1.hashCode()).isNotZero();
assertThat(membre2.hashCode()).isNotZero();
}
@Test
@DisplayName("Test des propriétés nulles")
void testProprietesNulles() {
// Given
Membre membre = new Membre();
// When & Then
assertThat(membre.getNumeroMembre()).isNull();
assertThat(membre.getPrenom()).isNull();
assertThat(membre.getNom()).isNull();
assertThat(membre.getEmail()).isNull();
assertThat(membre.getTelephone()).isNull();
assertThat(membre.getDateNaissance()).isNull();
assertThat(membre.getDateAdhesion()).isNull();
// Le champ actif a une valeur par défaut à true dans l'entité
// assertThat(membre.getActif()).isNull();
}
@Test
@DisplayName("Test de la méthode preUpdate")
void testPreUpdate() {
// Given
Membre membre = new Membre();
assertThat(membre.getDateModification()).isNull();
// When
membre.preUpdate();
// Then
assertThat(membre.getDateModification()).isNotNull();
}
}

View File

@@ -1,184 +0,0 @@
package dev.lions.unionflow.server.repository;
import dev.lions.unionflow.server.entity.Membre;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests d'intégration pour MembreRepository
*
* @author Lions Dev Team
* @since 2025-01-10
*/
@QuarkusTest
@DisplayName("Tests d'intégration MembreRepository")
class MembreRepositoryIntegrationTest {
@Inject
MembreRepository membreRepository;
private Membre membreTest;
@BeforeEach
@Transactional
void setUp() {
// Nettoyer la base de données
membreRepository.deleteAll();
// Créer un membre de test
membreTest = Membre.builder()
.numeroMembre("UF2025-TEST01")
.prenom("Jean")
.nom("Dupont")
.email("jean.dupont@test.com")
.telephone("221701234567")
.dateNaissance(LocalDate.of(1990, 5, 15))
.dateAdhesion(LocalDate.now())
.actif(true)
.build();
membreRepository.persist(membreTest);
}
@Test
@DisplayName("Test findByEmail - Membre existant")
@Transactional
void testFindByEmailExistant() {
// When
Optional<Membre> result = membreRepository.findByEmail("jean.dupont@test.com");
// Then
assertThat(result).isPresent();
assertThat(result.get().getPrenom()).isEqualTo("Jean");
assertThat(result.get().getNom()).isEqualTo("Dupont");
}
@Test
@DisplayName("Test findByEmail - Membre inexistant")
@Transactional
void testFindByEmailInexistant() {
// When
Optional<Membre> result = membreRepository.findByEmail("inexistant@test.com");
// Then
assertThat(result).isEmpty();
}
@Test
@DisplayName("Test findByNumeroMembre - Membre existant")
@Transactional
void testFindByNumeroMembreExistant() {
// When
Optional<Membre> result = membreRepository.findByNumeroMembre("UF2025-TEST01");
// Then
assertThat(result).isPresent();
assertThat(result.get().getPrenom()).isEqualTo("Jean");
assertThat(result.get().getNom()).isEqualTo("Dupont");
}
@Test
@DisplayName("Test findByNumeroMembre - Membre inexistant")
@Transactional
void testFindByNumeroMembreInexistant() {
// When
Optional<Membre> result = membreRepository.findByNumeroMembre("UF2025-INEXISTANT");
// Then
assertThat(result).isEmpty();
}
@Test
@DisplayName("Test findAllActifs - Seuls les membres actifs")
@Transactional
void testFindAllActifs() {
// Given - Ajouter un membre inactif
Membre membreInactif = Membre.builder()
.numeroMembre("UF2025-TEST02")
.prenom("Marie")
.nom("Martin")
.email("marie.martin@test.com")
.telephone("221701234568")
.dateNaissance(LocalDate.of(1985, 8, 20))
.dateAdhesion(LocalDate.now())
.actif(false)
.build();
membreRepository.persist(membreInactif);
// When
List<Membre> result = membreRepository.findAllActifs();
// Then
assertThat(result).hasSize(1);
assertThat(result.get(0).getActif()).isTrue();
assertThat(result.get(0).getPrenom()).isEqualTo("Jean");
}
@Test
@DisplayName("Test countActifs - Nombre de membres actifs")
@Transactional
void testCountActifs() {
// When
long count = membreRepository.countActifs();
// Then
assertThat(count).isEqualTo(1);
}
@Test
@DisplayName("Test findByNomOrPrenom - Recherche par nom")
@Transactional
void testFindByNomOrPrenomParNom() {
// When
List<Membre> result = membreRepository.findByNomOrPrenom("dupont");
// Then
assertThat(result).hasSize(1);
assertThat(result.get(0).getNom()).isEqualTo("Dupont");
}
@Test
@DisplayName("Test findByNomOrPrenom - Recherche par prénom")
@Transactional
void testFindByNomOrPrenomParPrenom() {
// When
List<Membre> result = membreRepository.findByNomOrPrenom("jean");
// Then
assertThat(result).hasSize(1);
assertThat(result.get(0).getPrenom()).isEqualTo("Jean");
}
@Test
@DisplayName("Test findByNomOrPrenom - Aucun résultat")
@Transactional
void testFindByNomOrPrenomAucunResultat() {
// When
List<Membre> result = membreRepository.findByNomOrPrenom("inexistant");
// Then
assertThat(result).isEmpty();
}
@Test
@DisplayName("Test findByNomOrPrenom - Recherche insensible à la casse")
@Transactional
void testFindByNomOrPrenomCaseInsensitive() {
// When
List<Membre> result = membreRepository.findByNomOrPrenom("DUPONT");
// Then
assertThat(result).hasSize(1);
assertThat(result.get(0).getNom()).isEqualTo("Dupont");
}
}

View File

@@ -1,107 +0,0 @@
package dev.lions.unionflow.server.repository;
import dev.lions.unionflow.server.entity.Membre;
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.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/**
* Tests pour MembreRepository
*
* @author Lions Dev Team
* @since 2025-01-10
*/
@ExtendWith(MockitoExtension.class)
@DisplayName("Tests MembreRepository")
class MembreRepositoryTest {
@Mock
MembreRepository membreRepository;
private Membre membreTest;
private Membre membreInactif;
@BeforeEach
void setUp() {
// Créer des membres de test
membreTest = Membre.builder()
.numeroMembre("UF2025-TEST01")
.prenom("Jean")
.nom("Dupont")
.email("jean.dupont@test.com")
.telephone("221701234567")
.dateNaissance(LocalDate.of(1990, 5, 15))
.dateAdhesion(LocalDate.now())
.actif(true)
.build();
membreInactif = Membre.builder()
.numeroMembre("UF2025-TEST02")
.prenom("Marie")
.nom("Martin")
.email("marie.martin@test.com")
.telephone("221701234568")
.dateNaissance(LocalDate.of(1985, 8, 20))
.dateAdhesion(LocalDate.now())
.actif(false)
.build();
}
@Test
@DisplayName("Test de l'existence de la classe MembreRepository")
void testMembreRepositoryExists() {
// Given & When & Then
assertThat(MembreRepository.class).isNotNull();
assertThat(membreRepository).isNotNull();
}
@Test
@DisplayName("Test des méthodes du repository")
void testRepositoryMethods() throws NoSuchMethodException {
// Given & When & Then
assertThat(MembreRepository.class.getMethod("findByEmail", String.class)).isNotNull();
assertThat(MembreRepository.class.getMethod("findByNumeroMembre", String.class)).isNotNull();
assertThat(MembreRepository.class.getMethod("findAllActifs")).isNotNull();
assertThat(MembreRepository.class.getMethod("countActifs")).isNotNull();
assertThat(MembreRepository.class.getMethod("findByNomOrPrenom", String.class)).isNotNull();
}
@Test
@DisplayName("Test de l'annotation ApplicationScoped")
void testApplicationScopedAnnotation() {
// Given & When & Then
assertThat(MembreRepository.class.getAnnotation(jakarta.enterprise.context.ApplicationScoped.class))
.isNotNull();
}
@Test
@DisplayName("Test de l'implémentation PanacheRepository")
void testPanacheRepositoryImplementation() {
// Given & When & Then
assertThat(io.quarkus.hibernate.orm.panache.PanacheRepository.class)
.isAssignableFrom(MembreRepository.class);
}
@Test
@DisplayName("Test de la création d'instance")
void testInstanceCreation() {
// Given & When
MembreRepository repository = new MembreRepository();
// Then
assertThat(repository).isNotNull();
assertThat(repository).isInstanceOf(io.quarkus.hibernate.orm.panache.PanacheRepository.class);
}
}

View File

@@ -1,375 +0,0 @@
package dev.lions.unionflow.server.resource;
import dev.lions.unionflow.server.api.dto.solidarite.aide.AideDTO;
import dev.lions.unionflow.server.api.enums.solidarite.StatutAide;
import dev.lions.unionflow.server.service.AideService;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectMock;
import io.quarkus.test.security.TestSecurity;
import io.restassured.http.ContentType;
import jakarta.ws.rs.NotFoundException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;
/**
* Tests d'intégration pour AideResource
*
* @author UnionFlow Team
* @version 1.0
* @since 2025-01-15
*/
@QuarkusTest
@DisplayName("AideResource - Tests d'intégration")
class AideResourceTest {
@InjectMock
AideService aideService;
private AideDTO aideDTOTest;
private List<AideDTO> listeAidesTest;
@BeforeEach
void setUp() {
// DTO de test
aideDTOTest = new AideDTO();
aideDTOTest.setId(UUID.randomUUID());
aideDTOTest.setNumeroReference("AIDE-2025-TEST01");
aideDTOTest.setTitre("Aide médicale urgente");
aideDTOTest.setDescription("Demande d'aide pour frais médicaux urgents");
aideDTOTest.setTypeAide("MEDICALE");
aideDTOTest.setMontantDemande(new BigDecimal("500000.00"));
aideDTOTest.setStatut("EN_ATTENTE");
aideDTOTest.setPriorite("URGENTE");
aideDTOTest.setMembreDemandeurId(UUID.randomUUID());
aideDTOTest.setAssociationId(UUID.randomUUID());
aideDTOTest.setActif(true);
// Liste de test
listeAidesTest = Arrays.asList(aideDTOTest);
}
@Nested
@DisplayName("Tests des endpoints CRUD")
class CrudEndpointsTests {
@Test
@TestSecurity(user = "admin", roles = {"admin"})
@DisplayName("GET /api/aides - Liste des aides")
void testListerAides() {
// Given
when(aideService.listerAidesActives(0, 20)).thenReturn(listeAidesTest);
// When & Then
given()
.when()
.get("/api/aides")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("size()", is(1))
.body("[0].titre", equalTo("Aide médicale urgente"))
.body("[0].statut", equalTo("EN_ATTENTE"));
}
@Test
@TestSecurity(user = "admin", roles = {"admin"})
@DisplayName("GET /api/aides/{id} - Récupération par ID")
void testObtenirAideParId() {
// Given
when(aideService.obtenirAideParId(1L)).thenReturn(aideDTOTest);
// When & Then
given()
.when()
.get("/api/aides/1")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("titre", equalTo("Aide médicale urgente"))
.body("numeroReference", equalTo("AIDE-2025-TEST01"));
}
@Test
@TestSecurity(user = "admin", roles = {"admin"})
@DisplayName("GET /api/aides/{id} - Aide non trouvée")
void testObtenirAideParId_NonTrouvee() {
// Given
when(aideService.obtenirAideParId(999L)).thenThrow(new NotFoundException("Demande d'aide non trouvée"));
// When & Then
given()
.when()
.get("/api/aides/999")
.then()
.statusCode(404)
.contentType(ContentType.JSON)
.body("error", equalTo("Demande d'aide non trouvée"));
}
@Test
@TestSecurity(user = "admin", roles = {"admin"})
@DisplayName("POST /api/aides - Création d'aide")
void testCreerAide() {
// Given
when(aideService.creerAide(any(AideDTO.class))).thenReturn(aideDTOTest);
// When & Then
given()
.contentType(ContentType.JSON)
.body(aideDTOTest)
.when()
.post("/api/aides")
.then()
.statusCode(201)
.contentType(ContentType.JSON)
.body("titre", equalTo("Aide médicale urgente"))
.body("numeroReference", equalTo("AIDE-2025-TEST01"));
}
@Test
@TestSecurity(user = "admin", roles = {"admin"})
@DisplayName("PUT /api/aides/{id} - Mise à jour d'aide")
void testMettreAJourAide() {
// Given
AideDTO aideMiseAJour = new AideDTO();
aideMiseAJour.setTitre("Titre modifié");
aideMiseAJour.setDescription("Description modifiée");
when(aideService.mettreAJourAide(eq(1L), any(AideDTO.class))).thenReturn(aideMiseAJour);
// When & Then
given()
.contentType(ContentType.JSON)
.body(aideMiseAJour)
.when()
.put("/api/aides/1")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("titre", equalTo("Titre modifié"));
}
}
@Nested
@DisplayName("Tests des endpoints métier")
class EndpointsMetierTests {
@Test
@TestSecurity(user = "evaluateur", roles = {"evaluateur_aide"})
@DisplayName("POST /api/aides/{id}/approuver - Approbation d'aide")
void testApprouverAide() {
// Given
AideDTO aideApprouvee = new AideDTO();
aideApprouvee.setStatut("APPROUVEE");
aideApprouvee.setMontantApprouve(new BigDecimal("400000.00"));
when(aideService.approuverAide(eq(1L), any(BigDecimal.class), anyString()))
.thenReturn(aideApprouvee);
Map<String, Object> approbationData = Map.of(
"montantApprouve", "400000.00",
"commentaires", "Aide approuvée après évaluation"
);
// When & Then
given()
.contentType(ContentType.JSON)
.body(approbationData)
.when()
.post("/api/aides/1/approuver")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("statut", equalTo("APPROUVEE"));
}
@Test
@TestSecurity(user = "evaluateur", roles = {"evaluateur_aide"})
@DisplayName("POST /api/aides/{id}/rejeter - Rejet d'aide")
void testRejeterAide() {
// Given
AideDTO aideRejetee = new AideDTO();
aideRejetee.setStatut("REJETEE");
aideRejetee.setRaisonRejet("Dossier incomplet");
when(aideService.rejeterAide(eq(1L), anyString())).thenReturn(aideRejetee);
Map<String, String> rejetData = Map.of(
"raisonRejet", "Dossier incomplet"
);
// When & Then
given()
.contentType(ContentType.JSON)
.body(rejetData)
.when()
.post("/api/aides/1/rejeter")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("statut", equalTo("REJETEE"));
}
@Test
@TestSecurity(user = "tresorier", roles = {"tresorier"})
@DisplayName("POST /api/aides/{id}/verser - Versement d'aide")
void testMarquerCommeVersee() {
// Given
AideDTO aideVersee = new AideDTO();
aideVersee.setStatut("VERSEE");
aideVersee.setMontantVerse(new BigDecimal("400000.00"));
when(aideService.marquerCommeVersee(eq(1L), any(BigDecimal.class), anyString(), anyString()))
.thenReturn(aideVersee);
Map<String, Object> versementData = Map.of(
"montantVerse", "400000.00",
"modeVersement", "MOBILE_MONEY",
"numeroTransaction", "TXN123456789"
);
// When & Then
given()
.contentType(ContentType.JSON)
.body(versementData)
.when()
.post("/api/aides/1/verser")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("statut", equalTo("VERSEE"));
}
}
@Nested
@DisplayName("Tests des endpoints de recherche")
class EndpointsRechercheTests {
@Test
@TestSecurity(user = "membre", roles = {"membre"})
@DisplayName("GET /api/aides/statut/{statut} - Filtrage par statut")
void testListerAidesParStatut() {
// Given
when(aideService.listerAidesParStatut(StatutAide.EN_ATTENTE, 0, 20))
.thenReturn(listeAidesTest);
// When & Then
given()
.when()
.get("/api/aides/statut/EN_ATTENTE")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("size()", is(1))
.body("[0].statut", equalTo("EN_ATTENTE"));
}
@Test
@TestSecurity(user = "membre", roles = {"membre"})
@DisplayName("GET /api/aides/membre/{membreId} - Aides d'un membre")
void testListerAidesParMembre() {
// Given
when(aideService.listerAidesParMembre(1L, 0, 20)).thenReturn(listeAidesTest);
// When & Then
given()
.when()
.get("/api/aides/membre/1")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("size()", is(1));
}
@Test
@TestSecurity(user = "membre", roles = {"membre"})
@DisplayName("GET /api/aides/recherche - Recherche textuelle")
void testRechercherAides() {
// Given
when(aideService.rechercherAides("médical", 0, 20)).thenReturn(listeAidesTest);
// When & Then
given()
.queryParam("q", "médical")
.when()
.get("/api/aides/recherche")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("size()", is(1));
}
@Test
@TestSecurity(user = "admin", roles = {"admin"})
@DisplayName("GET /api/aides/statistiques - Statistiques")
void testObtenirStatistiques() {
// Given
Map<String, Object> statistiques = Map.of(
"total", 100L,
"enAttente", 25L,
"approuvees", 50L,
"versees", 20L
);
when(aideService.obtenirStatistiquesGlobales()).thenReturn(statistiques);
// When & Then
given()
.when()
.get("/api/aides/statistiques")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("total", equalTo(100))
.body("enAttente", equalTo(25))
.body("approuvees", equalTo(50))
.body("versees", equalTo(20));
}
}
@Nested
@DisplayName("Tests de sécurité")
class SecurityTests {
@Test
@DisplayName("Accès non authentifié - 401")
void testAccesNonAuthentifie() {
given()
.when()
.get("/api/aides")
.then()
.statusCode(401);
}
@Test
@TestSecurity(user = "membre", roles = {"membre"})
@DisplayName("Accès non autorisé pour approbation - 403")
void testAccesNonAutorisePourApprobation() {
Map<String, Object> approbationData = Map.of(
"montantApprouve", "400000.00",
"commentaires", "Test"
);
given()
.contentType(ContentType.JSON)
.body(approbationData)
.when()
.post("/api/aides/1/approuver")
.then()
.statusCode(403);
}
}
}

View File

@@ -1,329 +0,0 @@
package dev.lions.unionflow.server.resource;
import dev.lions.unionflow.server.api.dto.finance.CotisationDTO;
import dev.lions.unionflow.server.entity.Cotisation;
import dev.lions.unionflow.server.entity.Membre;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import jakarta.transaction.Transactional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Tests d'intégration pour CotisationResource
* Teste tous les endpoints REST de l'API cotisations
*
* @author UnionFlow Team
* @version 1.0
* @since 2025-01-15
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@DisplayName("Tests d'intégration - API Cotisations")
class CotisationResourceTest {
private static Long membreTestId;
private static Long cotisationTestId;
private static String numeroReferenceTest;
@BeforeEach
@Transactional
void setUp() {
// Nettoyage et création des données de test
Cotisation.deleteAll();
Membre.deleteAll();
// Création d'un membre de test
Membre membreTest = new Membre();
membreTest.setNumeroMembre("MBR-TEST-001");
membreTest.setNom("Dupont");
membreTest.setPrenom("Jean");
membreTest.setEmail("jean.dupont@test.com");
membreTest.setTelephone("+225070123456");
membreTest.setDateNaissance(LocalDate.of(1985, 5, 15));
membreTest.setActif(true);
membreTest.persist();
membreTestId = membreTest.id;
}
@Test
@org.junit.jupiter.api.Order(1)
@DisplayName("POST /api/cotisations - Création d'une cotisation")
void testCreateCotisation() {
CotisationDTO nouvelleCotisation = new CotisationDTO();
nouvelleCotisation.setMembreId(UUID.fromString(membreTestId.toString()));
nouvelleCotisation.setTypeCotisation("MENSUELLE");
nouvelleCotisation.setMontantDu(new BigDecimal("25000.00"));
nouvelleCotisation.setDateEcheance(LocalDate.now().plusDays(30));
nouvelleCotisation.setDescription("Cotisation mensuelle janvier 2025");
nouvelleCotisation.setPeriode("Janvier 2025");
nouvelleCotisation.setAnnee(2025);
nouvelleCotisation.setMois(1);
given()
.contentType(ContentType.JSON)
.body(nouvelleCotisation)
.when()
.post("/api/cotisations")
.then()
.statusCode(201)
.body("numeroReference", notNullValue())
.body("membreId", equalTo(membreTestId.toString()))
.body("typeCotisation", equalTo("MENSUELLE"))
.body("montantDu", equalTo(25000.00f))
.body("montantPaye", equalTo(0.0f))
.body("statut", equalTo("EN_ATTENTE"))
.body("codeDevise", equalTo("XOF"))
.body("annee", equalTo(2025))
.body("mois", equalTo(1));
}
@Test
@org.junit.jupiter.api.Order(2)
@DisplayName("GET /api/cotisations - Liste des cotisations")
void testGetAllCotisations() {
given()
.queryParam("page", 0)
.queryParam("size", 10)
.when()
.get("/api/cotisations")
.then()
.statusCode(200)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@org.junit.jupiter.api.Order(3)
@DisplayName("GET /api/cotisations/{id} - Récupération par ID")
void testGetCotisationById() {
// Créer d'abord une cotisation
CotisationDTO cotisation = createTestCotisation();
cotisationTestId = Long.valueOf(cotisation.getId().toString());
given()
.pathParam("id", cotisationTestId)
.when()
.get("/api/cotisations/{id}")
.then()
.statusCode(200)
.body("id", equalTo(cotisationTestId.toString()))
.body("typeCotisation", equalTo("MENSUELLE"));
}
@Test
@org.junit.jupiter.api.Order(4)
@DisplayName("GET /api/cotisations/reference/{numeroReference} - Récupération par référence")
void testGetCotisationByReference() {
// Utiliser la cotisation créée précédemment
if (numeroReferenceTest == null) {
CotisationDTO cotisation = createTestCotisation();
numeroReferenceTest = cotisation.getNumeroReference();
}
given()
.pathParam("numeroReference", numeroReferenceTest)
.when()
.get("/api/cotisations/reference/{numeroReference}")
.then()
.statusCode(200)
.body("numeroReference", equalTo(numeroReferenceTest))
.body("typeCotisation", equalTo("MENSUELLE"));
}
@Test
@org.junit.jupiter.api.Order(5)
@DisplayName("PUT /api/cotisations/{id} - Mise à jour d'une cotisation")
void testUpdateCotisation() {
// Créer une cotisation si nécessaire
if (cotisationTestId == null) {
CotisationDTO cotisation = createTestCotisation();
cotisationTestId = Long.valueOf(cotisation.getId().toString());
}
CotisationDTO cotisationMiseAJour = new CotisationDTO();
cotisationMiseAJour.setTypeCotisation("TRIMESTRIELLE");
cotisationMiseAJour.setMontantDu(new BigDecimal("75000.00"));
cotisationMiseAJour.setDescription("Cotisation trimestrielle Q1 2025");
cotisationMiseAJour.setObservations("Mise à jour du type de cotisation");
given()
.contentType(ContentType.JSON)
.pathParam("id", cotisationTestId)
.body(cotisationMiseAJour)
.when()
.put("/api/cotisations/{id}")
.then()
.statusCode(200)
.body("typeCotisation", equalTo("TRIMESTRIELLE"))
.body("montantDu", equalTo(75000.00f))
.body("observations", equalTo("Mise à jour du type de cotisation"));
}
@Test
@org.junit.jupiter.api.Order(6)
@DisplayName("GET /api/cotisations/membre/{membreId} - Cotisations d'un membre")
void testGetCotisationsByMembre() {
given()
.pathParam("membreId", membreTestId)
.queryParam("page", 0)
.queryParam("size", 10)
.when()
.get("/api/cotisations/membre/{membreId}")
.then()
.statusCode(200)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@org.junit.jupiter.api.Order(7)
@DisplayName("GET /api/cotisations/statut/{statut} - Cotisations par statut")
void testGetCotisationsByStatut() {
given()
.pathParam("statut", "EN_ATTENTE")
.queryParam("page", 0)
.queryParam("size", 10)
.when()
.get("/api/cotisations/statut/{statut}")
.then()
.statusCode(200)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@org.junit.jupiter.api.Order(8)
@DisplayName("GET /api/cotisations/en-retard - Cotisations en retard")
void testGetCotisationsEnRetard() {
given()
.queryParam("page", 0)
.queryParam("size", 10)
.when()
.get("/api/cotisations/en-retard")
.then()
.statusCode(200)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@org.junit.jupiter.api.Order(9)
@DisplayName("GET /api/cotisations/recherche - Recherche avancée")
void testRechercherCotisations() {
given()
.queryParam("membreId", membreTestId)
.queryParam("statut", "EN_ATTENTE")
.queryParam("annee", 2025)
.queryParam("page", 0)
.queryParam("size", 10)
.when()
.get("/api/cotisations/recherche")
.then()
.statusCode(200)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@org.junit.jupiter.api.Order(10)
@DisplayName("GET /api/cotisations/stats - Statistiques des cotisations")
void testGetStatistiquesCotisations() {
given()
.when()
.get("/api/cotisations/stats")
.then()
.statusCode(200)
.body("totalCotisations", notNullValue())
.body("cotisationsPayees", notNullValue())
.body("cotisationsEnRetard", notNullValue())
.body("tauxPaiement", notNullValue());
}
@Test
@org.junit.jupiter.api.Order(11)
@DisplayName("DELETE /api/cotisations/{id} - Suppression d'une cotisation")
void testDeleteCotisation() {
// Créer une cotisation si nécessaire
if (cotisationTestId == null) {
CotisationDTO cotisation = createTestCotisation();
cotisationTestId = Long.valueOf(cotisation.getId().toString());
}
given()
.pathParam("id", cotisationTestId)
.when()
.delete("/api/cotisations/{id}")
.then()
.statusCode(204);
// Vérifier que la cotisation est marquée comme annulée
given()
.pathParam("id", cotisationTestId)
.when()
.get("/api/cotisations/{id}")
.then()
.statusCode(200)
.body("statut", equalTo("ANNULEE"));
}
@Test
@DisplayName("GET /api/cotisations/{id} - Cotisation inexistante")
void testGetCotisationByIdNotFound() {
given()
.pathParam("id", 99999L)
.when()
.get("/api/cotisations/{id}")
.then()
.statusCode(404)
.body("error", equalTo("Cotisation non trouvée"));
}
@Test
@DisplayName("POST /api/cotisations - Données invalides")
void testCreateCotisationInvalidData() {
CotisationDTO cotisationInvalide = new CotisationDTO();
// Données manquantes ou invalides
cotisationInvalide.setTypeCotisation("");
cotisationInvalide.setMontantDu(new BigDecimal("-100"));
given()
.contentType(ContentType.JSON)
.body(cotisationInvalide)
.when()
.post("/api/cotisations")
.then()
.statusCode(400);
}
/**
* Méthode utilitaire pour créer une cotisation de test
*/
private CotisationDTO createTestCotisation() {
CotisationDTO cotisation = new CotisationDTO();
cotisation.setMembreId(UUID.fromString(membreTestId.toString()));
cotisation.setTypeCotisation("MENSUELLE");
cotisation.setMontantDu(new BigDecimal("25000.00"));
cotisation.setDateEcheance(LocalDate.now().plusDays(30));
cotisation.setDescription("Cotisation de test");
cotisation.setPeriode("Test 2025");
cotisation.setAnnee(2025);
cotisation.setMois(1);
return given()
.contentType(ContentType.JSON)
.body(cotisation)
.when()
.post("/api/cotisations")
.then()
.statusCode(201)
.extract()
.as(CotisationDTO.class);
}
}

View File

@@ -1,413 +0,0 @@
package dev.lions.unionflow.server.resource;
import dev.lions.unionflow.server.entity.Evenement;
import dev.lions.unionflow.server.entity.Evenement.StatutEvenement;
import dev.lions.unionflow.server.entity.Evenement.TypeEvenement;
import dev.lions.unionflow.server.entity.Membre;
import dev.lions.unionflow.server.entity.Organisation;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.security.TestSecurity;
import io.restassured.http.ContentType;
import jakarta.transaction.Transactional;
import org.junit.jupiter.api.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Tests d'intégration pour EvenementResource
*
* Tests complets de l'API REST des événements avec authentification
* et validation des permissions. Optimisé pour l'intégration mobile.
*
* @author UnionFlow Team
* @version 1.0
* @since 2025-01-15
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@DisplayName("Tests d'intégration - API Événements")
class EvenementResourceTest {
private static Long evenementTestId;
private static Long organisationTestId;
private static Long membreTestId;
@BeforeAll
@Transactional
static void setupTestData() {
// Créer une organisation de test
Organisation organisation = Organisation.builder()
.nom("Union Test API")
.typeOrganisation("ASSOCIATION")
.statut("ACTIVE")
.email("test-api@union.com")
.telephone("0123456789")
.adresse("123 Rue de Test")
.codePostal("75001")
.ville("Paris")
.pays("France")
.actif(true)
.creePar("test@unionflow.dev")
.dateCreation(LocalDateTime.now())
.build();
organisation.persist();
organisationTestId = organisation.id;
// Créer un membre de test
Membre membre = Membre.builder()
.numeroMembre("UF2025-API01")
.prenom("Marie")
.nom("Martin")
.email("marie.martin@test.com")
.telephone("0987654321")
.dateNaissance(LocalDate.of(1990, 5, 15))
.dateAdhesion(LocalDate.now())
.actif(true)
.organisation(organisation)
.build();
membre.persist();
membreTestId = membre.id;
// Créer un événement de test
Evenement evenement = Evenement.builder()
.titre("Conférence API Test")
.description("Conférence de test pour l'API")
.dateDebut(LocalDateTime.now().plusDays(15))
.dateFin(LocalDateTime.now().plusDays(15).plusHours(2))
.lieu("Centre de conférence Test")
.typeEvenement(TypeEvenement.CONFERENCE)
.statut(StatutEvenement.PLANIFIE)
.capaciteMax(50)
.prix(BigDecimal.valueOf(15.00))
.inscriptionRequise(true)
.visiblePublic(true)
.actif(true)
.organisation(organisation)
.organisateur(membre)
.creePar("test@unionflow.dev")
.dateCreation(LocalDateTime.now())
.build();
evenement.persist();
evenementTestId = evenement.id;
}
@Test
@Order(1)
@DisplayName("GET /api/evenements - Lister événements (authentifié)")
@TestSecurity(user = "marie.martin@test.com", roles = {"MEMBRE"})
void testListerEvenements_Authentifie() {
given()
.when()
.get("/api/evenements")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("size()", greaterThanOrEqualTo(1))
.body("[0].titre", notNullValue())
.body("[0].dateDebut", notNullValue())
.body("[0].statut", notNullValue());
}
@Test
@Order(2)
@DisplayName("GET /api/evenements - Non authentifié")
void testListerEvenements_NonAuthentifie() {
given()
.when()
.get("/api/evenements")
.then()
.statusCode(401);
}
@Test
@Order(3)
@DisplayName("GET /api/evenements/{id} - Récupérer événement")
@TestSecurity(user = "marie.martin@test.com", roles = {"MEMBRE"})
void testObtenirEvenement() {
given()
.pathParam("id", evenementTestId)
.when()
.get("/api/evenements/{id}")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("id", equalTo(evenementTestId.intValue()))
.body("titre", equalTo("Conférence API Test"))
.body("description", equalTo("Conférence de test pour l'API"))
.body("typeEvenement", equalTo("CONFERENCE"))
.body("statut", equalTo("PLANIFIE"))
.body("capaciteMax", equalTo(50))
.body("prix", equalTo(15.0f))
.body("inscriptionRequise", equalTo(true))
.body("visiblePublic", equalTo(true))
.body("actif", equalTo(true));
}
@Test
@Order(4)
@DisplayName("GET /api/evenements/{id} - Événement non trouvé")
@TestSecurity(user = "marie.martin@test.com", roles = {"MEMBRE"})
void testObtenirEvenement_NonTrouve() {
given()
.pathParam("id", 99999)
.when()
.get("/api/evenements/{id}")
.then()
.statusCode(404)
.body("error", equalTo("Événement non trouvé"));
}
@Test
@Order(5)
@DisplayName("POST /api/evenements - Créer événement (organisateur)")
@TestSecurity(user = "marie.martin@test.com", roles = {"ORGANISATEUR_EVENEMENT"})
void testCreerEvenement_Organisateur() {
String nouvelEvenement = String.format("""
{
"titre": "Nouvel Événement Test",
"description": "Description du nouvel événement",
"dateDebut": "%s",
"dateFin": "%s",
"lieu": "Lieu de test",
"typeEvenement": "FORMATION",
"capaciteMax": 30,
"prix": 20.00,
"inscriptionRequise": true,
"visiblePublic": true,
"organisation": {"id": %d},
"organisateur": {"id": %d}
}
""",
LocalDateTime.now().plusDays(20).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
LocalDateTime.now().plusDays(20).plusHours(3).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
organisationTestId,
membreTestId
);
given()
.contentType(ContentType.JSON)
.body(nouvelEvenement)
.when()
.post("/api/evenements")
.then()
.statusCode(201)
.contentType(ContentType.JSON)
.body("titre", equalTo("Nouvel Événement Test"))
.body("typeEvenement", equalTo("FORMATION"))
.body("capaciteMax", equalTo(30))
.body("prix", equalTo(20.0f))
.body("actif", equalTo(true));
}
@Test
@Order(6)
@DisplayName("POST /api/evenements - Permissions insuffisantes")
@TestSecurity(user = "marie.martin@test.com", roles = {"MEMBRE"})
void testCreerEvenement_PermissionsInsuffisantes() {
String nouvelEvenement = """
{
"titre": "Événement Non Autorisé",
"description": "Test permissions",
"dateDebut": "2025-02-15T10:00:00",
"dateFin": "2025-02-15T12:00:00",
"lieu": "Lieu test",
"typeEvenement": "FORMATION"
}
""";
given()
.contentType(ContentType.JSON)
.body(nouvelEvenement)
.when()
.post("/api/evenements")
.then()
.statusCode(403);
}
@Test
@Order(7)
@DisplayName("PUT /api/evenements/{id} - Mettre à jour événement")
@TestSecurity(user = "admin@unionflow.dev", roles = {"ADMIN"})
void testMettreAJourEvenement_Admin() {
String evenementModifie = String.format("""
{
"titre": "Conférence API Test - Modifiée",
"description": "Description mise à jour",
"dateDebut": "%s",
"dateFin": "%s",
"lieu": "Nouveau lieu",
"typeEvenement": "CONFERENCE",
"capaciteMax": 75,
"prix": 25.00,
"inscriptionRequise": true,
"visiblePublic": true
}
""",
LocalDateTime.now().plusDays(16).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
LocalDateTime.now().plusDays(16).plusHours(3).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
);
given()
.pathParam("id", evenementTestId)
.contentType(ContentType.JSON)
.body(evenementModifie)
.when()
.put("/api/evenements/{id}")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("titre", equalTo("Conférence API Test - Modifiée"))
.body("description", equalTo("Description mise à jour"))
.body("lieu", equalTo("Nouveau lieu"))
.body("capaciteMax", equalTo(75))
.body("prix", equalTo(25.0f));
}
@Test
@Order(8)
@DisplayName("GET /api/evenements/a-venir - Événements à venir")
@TestSecurity(user = "marie.martin@test.com", roles = {"MEMBRE"})
void testEvenementsAVenir() {
given()
.queryParam("page", 0)
.queryParam("size", 10)
.when()
.get("/api/evenements/a-venir")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@Order(9)
@DisplayName("GET /api/evenements/publics - Événements publics (non authentifié)")
void testEvenementsPublics_NonAuthentifie() {
given()
.queryParam("page", 0)
.queryParam("size", 20)
.when()
.get("/api/evenements/publics")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@Order(10)
@DisplayName("GET /api/evenements/recherche - Recherche d'événements")
@TestSecurity(user = "marie.martin@test.com", roles = {"MEMBRE"})
void testRechercherEvenements() {
given()
.queryParam("q", "Conférence")
.queryParam("page", 0)
.queryParam("size", 20)
.when()
.get("/api/evenements/recherche")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@Order(11)
@DisplayName("GET /api/evenements/recherche - Terme de recherche manquant")
@TestSecurity(user = "marie.martin@test.com", roles = {"MEMBRE"})
void testRechercherEvenements_TermeManquant() {
given()
.queryParam("page", 0)
.queryParam("size", 20)
.when()
.get("/api/evenements/recherche")
.then()
.statusCode(400)
.body("error", equalTo("Le terme de recherche est obligatoire"));
}
@Test
@Order(12)
@DisplayName("GET /api/evenements/type/{type} - Événements par type")
@TestSecurity(user = "marie.martin@test.com", roles = {"MEMBRE"})
void testEvenementsParType() {
given()
.pathParam("type", "CONFERENCE")
.queryParam("page", 0)
.queryParam("size", 20)
.when()
.get("/api/evenements/type/{type}")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@Order(13)
@DisplayName("PATCH /api/evenements/{id}/statut - Changer statut")
@TestSecurity(user = "admin@unionflow.dev", roles = {"ADMIN"})
void testChangerStatut() {
given()
.pathParam("id", evenementTestId)
.queryParam("statut", "CONFIRME")
.when()
.patch("/api/evenements/{id}/statut")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("statut", equalTo("CONFIRME"));
}
@Test
@Order(14)
@DisplayName("GET /api/evenements/statistiques - Statistiques")
@TestSecurity(user = "admin@unionflow.dev", roles = {"ADMIN"})
void testObtenirStatistiques() {
given()
.when()
.get("/api/evenements/statistiques")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("total", notNullValue())
.body("actifs", notNullValue())
.body("timestamp", notNullValue());
}
@Test
@Order(15)
@DisplayName("DELETE /api/evenements/{id} - Supprimer événement")
@TestSecurity(user = "admin@unionflow.dev", roles = {"ADMIN"})
void testSupprimerEvenement() {
given()
.pathParam("id", evenementTestId)
.when()
.delete("/api/evenements/{id}")
.then()
.statusCode(204);
}
@Test
@Order(16)
@DisplayName("Pagination - Paramètres valides")
@TestSecurity(user = "marie.martin@test.com", roles = {"MEMBRE"})
void testPagination() {
given()
.queryParam("page", 0)
.queryParam("size", 5)
.queryParam("sort", "titre")
.queryParam("direction", "asc")
.when()
.get("/api/evenements")
.then()
.statusCode(200)
.contentType(ContentType.JSON);
}
}

View File

@@ -1,74 +0,0 @@
package dev.lions.unionflow.server.resource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Tests pour HealthResource
*
* @author Lions Dev Team
* @since 2025-01-10
*/
@QuarkusTest
@DisplayName("Tests HealthResource")
class HealthResourceTest {
@Test
@DisplayName("Test GET /api/status - Statut du serveur")
void testGetStatus() {
given()
.when()
.get("/api/status")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("status", equalTo("UP"))
.body("service", equalTo("UnionFlow Server"))
.body("version", equalTo("1.0.0"))
.body("message", equalTo("Serveur opérationnel"))
.body("timestamp", notNullValue());
}
@Test
@DisplayName("Test GET /api/status - Vérification de la structure de la réponse")
void testGetStatusStructure() {
given()
.when()
.get("/api/status")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("$", hasKey("status"))
.body("$", hasKey("service"))
.body("$", hasKey("version"))
.body("$", hasKey("timestamp"))
.body("$", hasKey("message"));
}
@Test
@DisplayName("Test GET /api/status - Vérification du Content-Type")
void testGetStatusContentType() {
given()
.when()
.get("/api/status")
.then()
.statusCode(200)
.contentType("application/json");
}
@Test
@DisplayName("Test GET /api/status - Réponse rapide")
void testGetStatusPerformance() {
given()
.when()
.get("/api/status")
.then()
.statusCode(200)
.time(lessThan(1000L)); // Moins d'1 seconde
}
}

View File

@@ -1,322 +0,0 @@
package dev.lions.unionflow.server.resource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Tests d'intégration complets pour MembreResource
* Couvre tous les endpoints et cas d'erreur
*/
@QuarkusTest
@DisplayName("Tests d'intégration complets MembreResource")
class MembreResourceCompleteIntegrationTest {
@Test
@DisplayName("POST /api/membres - Création avec email existant")
void testCreerMembreEmailExistant() {
// Créer un premier membre
String membreJson1 = """
{
"numeroMembre": "UF2025-EXIST01",
"prenom": "Premier",
"nom": "Membre",
"email": "existe@test.com",
"telephone": "221701234567",
"dateNaissance": "1990-05-15",
"dateAdhesion": "2025-01-10",
"actif": true
}
""";
given()
.contentType(ContentType.JSON)
.body(membreJson1)
.when()
.post("/api/membres")
.then()
.statusCode(anyOf(is(201), is(400))); // 201 si nouveau, 400 si existe déjà
// Essayer de créer un deuxième membre avec le même email
String membreJson2 = """
{
"numeroMembre": "UF2025-EXIST02",
"prenom": "Deuxieme",
"nom": "Membre",
"email": "existe@test.com",
"telephone": "221701234568",
"dateNaissance": "1985-08-20",
"dateAdhesion": "2025-01-10",
"actif": true
}
""";
given()
.contentType(ContentType.JSON)
.body(membreJson2)
.when()
.post("/api/membres")
.then()
.statusCode(400)
.body("message", notNullValue());
}
@Test
@DisplayName("POST /api/membres - Validation des champs obligatoires")
void testCreerMembreValidationChamps() {
// Test avec prénom manquant
String membreSansPrenom = """
{
"nom": "Test",
"email": "test.sans.prenom@test.com",
"telephone": "221701234567"
}
""";
given()
.contentType(ContentType.JSON)
.body(membreSansPrenom)
.when()
.post("/api/membres")
.then()
.statusCode(400);
// Test avec email invalide
String membreEmailInvalide = """
{
"prenom": "Test",
"nom": "Test",
"email": "email-invalide",
"telephone": "221701234567"
}
""";
given()
.contentType(ContentType.JSON)
.body(membreEmailInvalide)
.when()
.post("/api/membres")
.then()
.statusCode(400);
}
@Test
@DisplayName("PUT /api/membres/{id} - Mise à jour membre existant")
void testMettreAJourMembreExistant() {
// D'abord créer un membre
String membreOriginal = """
{
"numeroMembre": "UF2025-UPDATE01",
"prenom": "Original",
"nom": "Membre",
"email": "original.update@test.com",
"telephone": "221701234567",
"dateNaissance": "1990-05-15",
"dateAdhesion": "2025-01-10",
"actif": true
}
""";
// Créer le membre (peut réussir ou échouer si existe déjà)
given()
.contentType(ContentType.JSON)
.body(membreOriginal)
.when()
.post("/api/membres")
.then()
.statusCode(anyOf(is(201), is(400)));
// Essayer de mettre à jour avec ID 1 (peut exister ou non)
String membreMisAJour = """
{
"numeroMembre": "UF2025-UPDATE01",
"prenom": "Modifie",
"nom": "Membre",
"email": "modifie.update@test.com",
"telephone": "221701234567",
"dateNaissance": "1990-05-15",
"dateAdhesion": "2025-01-10",
"actif": true
}
""";
given()
.contentType(ContentType.JSON)
.body(membreMisAJour)
.when()
.put("/api/membres/1")
.then()
.statusCode(anyOf(is(200), is(400))); // 200 si trouvé, 400 si non trouvé
}
@Test
@DisplayName("PUT /api/membres/{id} - Membre inexistant")
void testMettreAJourMembreInexistant() {
String membreJson = """
{
"numeroMembre": "UF2025-INEXIST01",
"prenom": "Inexistant",
"nom": "Membre",
"email": "inexistant@test.com",
"telephone": "221701234567",
"dateNaissance": "1990-05-15",
"dateAdhesion": "2025-01-10",
"actif": true
}
""";
given()
.contentType(ContentType.JSON)
.body(membreJson)
.when()
.put("/api/membres/99999")
.then()
.statusCode(400)
.body("message", notNullValue());
}
@Test
@DisplayName("DELETE /api/membres/{id} - Désactiver membre existant")
void testDesactiverMembreExistant() {
// Essayer de désactiver le membre ID 1 (peut exister ou non)
given()
.when()
.delete("/api/membres/1")
.then()
.statusCode(anyOf(is(204), is(404))); // 204 si trouvé, 404 si non trouvé
}
@Test
@DisplayName("DELETE /api/membres/{id} - Membre inexistant")
void testDesactiverMembreInexistant() {
given()
.when()
.delete("/api/membres/99999")
.then()
.statusCode(404)
.body("message", notNullValue());
}
@Test
@DisplayName("GET /api/membres/{id} - Membre existant")
void testObtenirMembreExistant() {
// Essayer d'obtenir le membre ID 1 (peut exister ou non)
given()
.when()
.get("/api/membres/1")
.then()
.statusCode(anyOf(is(200), is(404))); // 200 si trouvé, 404 si non trouvé
}
@Test
@DisplayName("GET /api/membres/{id} - Membre inexistant")
void testObtenirMembreInexistant() {
given()
.when()
.get("/api/membres/99999")
.then()
.statusCode(404)
.body("message", equalTo("Membre non trouvé"));
}
@Test
@DisplayName("GET /api/membres/recherche - Recherche avec terme null")
void testRechercherMembresTermeNull() {
given()
.when()
.get("/api/membres/recherche")
.then()
.statusCode(400)
.body("message", equalTo("Le terme de recherche est requis"));
}
@Test
@DisplayName("GET /api/membres/recherche - Recherche avec terme valide")
void testRechercherMembresTermeValide() {
given()
.queryParam("q", "test")
.when()
.get("/api/membres/recherche")
.then()
.statusCode(200)
.contentType(ContentType.JSON);
}
@Test
@DisplayName("Test des headers HTTP")
void testHeadersHTTP() {
// Test avec différents Accept headers
given()
.accept(ContentType.JSON)
.when()
.get("/api/membres")
.then()
.statusCode(200)
.contentType(ContentType.JSON);
given()
.accept(ContentType.XML)
.when()
.get("/api/membres")
.then()
.statusCode(anyOf(is(200), is(406))); // 200 si supporté, 406 si non supporté
}
@Test
@DisplayName("Test des méthodes HTTP non supportées")
void testMethodesHTTPNonSupportees() {
// OPTIONS peut être supporté ou non
given()
.when()
.options("/api/membres")
.then()
.statusCode(anyOf(is(200), is(405)));
// HEAD peut être supporté ou non
given()
.when()
.head("/api/membres")
.then()
.statusCode(anyOf(is(200), is(405)));
}
@Test
@DisplayName("Test de performance et robustesse")
void testPerformanceEtRobustesse() {
// Test avec une grande quantité de données
StringBuilder largeJson = new StringBuilder();
largeJson.append("{");
largeJson.append("\"prenom\": \"").append("A".repeat(100)).append("\",");
largeJson.append("\"nom\": \"").append("B".repeat(100)).append("\",");
largeJson.append("\"email\": \"large.test@test.com\",");
largeJson.append("\"telephone\": \"221701234567\"");
largeJson.append("}");
given()
.contentType(ContentType.JSON)
.body(largeJson.toString())
.when()
.post("/api/membres")
.then()
.statusCode(anyOf(is(201), is(400))); // Peut réussir ou échouer selon la validation
}
@Test
@DisplayName("Test de gestion des erreurs serveur")
void testGestionErreursServeur() {
// Test avec des données qui peuvent causer des erreurs internes
String jsonMalformed = "{ invalid json }";
given()
.contentType(ContentType.JSON)
.body(jsonMalformed)
.when()
.post("/api/membres")
.then()
.statusCode(400); // Bad Request pour JSON malformé
}
}

View File

@@ -1,258 +0,0 @@
package dev.lions.unionflow.server.resource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* Tests d'intégration simples pour MembreResource
*
* @author Lions Dev Team
* @since 2025-01-10
*/
@QuarkusTest
@DisplayName("Tests d'intégration simples MembreResource")
class MembreResourceSimpleIntegrationTest {
@Test
@DisplayName("GET /api/membres - Lister tous les membres actifs")
void testListerMembres() {
given()
.when()
.get("/api/membres")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("$", notNullValue());
}
@Test
@DisplayName("GET /api/membres/999 - Membre non trouvé")
void testObtenirMembreNonTrouve() {
given()
.when()
.get("/api/membres/999")
.then()
.statusCode(404)
.contentType(ContentType.JSON)
.body("message", equalTo("Membre non trouvé"));
}
@Test
@DisplayName("POST /api/membres - Données invalides")
void testCreerMembreDonneesInvalides() {
String membreJson = """
{
"prenom": "",
"nom": "",
"email": "email-invalide",
"telephone": "123",
"dateNaissance": "2030-01-01"
}
""";
given()
.contentType(ContentType.JSON)
.body(membreJson)
.when()
.post("/api/membres")
.then()
.statusCode(400);
}
@Test
@DisplayName("PUT /api/membres/999 - Membre non trouvé")
void testMettreAJourMembreNonTrouve() {
String membreJson = """
{
"prenom": "Pierre",
"nom": "Martin",
"email": "pierre.martin@test.com"
}
""";
given()
.contentType(ContentType.JSON)
.body(membreJson)
.when()
.put("/api/membres/999")
.then()
.statusCode(400); // Simplement vérifier le code de statut
}
@Test
@DisplayName("DELETE /api/membres/999 - Membre non trouvé")
void testDesactiverMembreNonTrouve() {
given()
.when()
.delete("/api/membres/999")
.then()
.statusCode(404)
.contentType(ContentType.JSON)
.body("message", containsString("Membre non trouvé"));
}
@Test
@DisplayName("GET /api/membres/recherche - Terme manquant")
void testRechercherMembresTermeManquant() {
given()
.when()
.get("/api/membres/recherche")
.then()
.statusCode(400)
.contentType(ContentType.JSON)
.body("message", equalTo("Le terme de recherche est requis"));
}
@Test
@DisplayName("GET /api/membres/recherche - Terme vide")
void testRechercherMembresTermeVide() {
given()
.queryParam("q", " ")
.when()
.get("/api/membres/recherche")
.then()
.statusCode(400)
.contentType(ContentType.JSON)
.body("message", equalTo("Le terme de recherche est requis"));
}
@Test
@DisplayName("GET /api/membres/recherche - Recherche valide")
void testRechercherMembresValide() {
given()
.queryParam("q", "test")
.when()
.get("/api/membres/recherche")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("$", notNullValue());
}
@Test
@DisplayName("GET /api/membres/stats - Statistiques")
void testObtenirStatistiques() {
given()
.when()
.get("/api/membres/stats")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("nombreMembresActifs", notNullValue())
.body("timestamp", notNullValue());
}
@Test
@DisplayName("POST /api/membres - Membre valide")
void testCreerMembreValide() {
String membreJson = """
{
"prenom": "Jean",
"nom": "Dupont",
"email": "jean.dupont.test@example.com",
"telephone": "221701234567",
"dateNaissance": "1990-05-15",
"dateAdhesion": "2025-01-10"
}
""";
given()
.contentType(ContentType.JSON)
.body(membreJson)
.when()
.post("/api/membres")
.then()
.statusCode(anyOf(is(201), is(400))); // 201 si succès, 400 si email existe déjà
}
@Test
@DisplayName("Test des endpoints avec différents content types")
void testContentTypes() {
// Test avec Accept header
given()
.accept(ContentType.JSON)
.when()
.get("/api/membres")
.then()
.statusCode(200)
.contentType(ContentType.JSON);
// Test avec Accept header pour les stats
given()
.accept(ContentType.JSON)
.when()
.get("/api/membres/stats")
.then()
.statusCode(200)
.contentType(ContentType.JSON);
}
@Test
@DisplayName("Test des méthodes HTTP non supportées")
void testMethodesNonSupportees() {
// PATCH n'est pas supporté
given()
.when()
.patch("/api/membres/1")
.then()
.statusCode(405); // Method Not Allowed
}
@Test
@DisplayName("PUT /api/membres/{id} - Mise à jour avec données invalides")
void testMettreAJourMembreAvecDonneesInvalides() {
String membreInvalideJson = """
{
"prenom": "",
"nom": "",
"email": "email-invalide"
}
""";
given()
.contentType(ContentType.JSON)
.body(membreInvalideJson)
.when()
.put("/api/membres/1")
.then()
.statusCode(400);
}
@Test
@DisplayName("POST /api/membres - Données invalides")
void testCreerMembreAvecDonneesInvalides() {
String membreInvalideJson = """
{
"prenom": "",
"nom": "",
"email": "email-invalide"
}
""";
given()
.contentType(ContentType.JSON)
.body(membreInvalideJson)
.when()
.post("/api/membres")
.then()
.statusCode(400);
}
@Test
@DisplayName("GET /api/membres/recherche - Terme avec espaces seulement")
void testRechercherMembresTermeAvecEspacesUniquement() {
given()
.queryParam("q", " ")
.when()
.get("/api/membres/recherche")
.then()
.statusCode(400)
.contentType(ContentType.JSON)
.body("message", equalTo("Le terme de recherche est requis"));
}
}

View File

@@ -1,282 +0,0 @@
package dev.lions.unionflow.server.resource;
import dev.lions.unionflow.server.api.dto.membre.MembreDTO;
import dev.lions.unionflow.server.entity.Membre;
import dev.lions.unionflow.server.service.MembreService;
import io.quarkus.panache.common.Page;
import io.quarkus.panache.common.Sort;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import jakarta.ws.rs.core.Response;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;
/**
* Tests pour MembreResource
*
* @author Lions Dev Team
* @since 2025-01-10
*/
@ExtendWith(MockitoExtension.class)
@DisplayName("Tests MembreResource")
class MembreResourceTest {
@InjectMocks
MembreResource membreResource;
@Mock
MembreService membreService;
@Test
@DisplayName("Test de l'existence de la classe MembreResource")
void testMembreResourceExists() {
// Given & When & Then
assertThat(MembreResource.class).isNotNull();
assertThat(membreResource).isNotNull();
}
@Test
@DisplayName("Test de l'annotation Path")
void testPathAnnotation() {
// Given & When & Then
assertThat(MembreResource.class.getAnnotation(jakarta.ws.rs.Path.class))
.isNotNull();
assertThat(MembreResource.class.getAnnotation(jakarta.ws.rs.Path.class).value())
.isEqualTo("/api/membres");
}
@Test
@DisplayName("Test de l'annotation ApplicationScoped")
void testApplicationScopedAnnotation() {
// Given & When & Then
assertThat(MembreResource.class.getAnnotation(jakarta.enterprise.context.ApplicationScoped.class))
.isNotNull();
}
@Test
@DisplayName("Test de l'annotation Produces")
void testProducesAnnotation() {
// Given & When & Then
assertThat(MembreResource.class.getAnnotation(jakarta.ws.rs.Produces.class))
.isNotNull();
assertThat(MembreResource.class.getAnnotation(jakarta.ws.rs.Produces.class).value())
.contains("application/json");
}
@Test
@DisplayName("Test de l'annotation Consumes")
void testConsumesAnnotation() {
// Given & When & Then
assertThat(MembreResource.class.getAnnotation(jakarta.ws.rs.Consumes.class))
.isNotNull();
assertThat(MembreResource.class.getAnnotation(jakarta.ws.rs.Consumes.class).value())
.contains("application/json");
}
@Test
@DisplayName("Test des méthodes du resource")
void testResourceMethods() throws NoSuchMethodException {
// Given & When & Then
assertThat(MembreResource.class.getMethod("listerMembres")).isNotNull();
assertThat(MembreResource.class.getMethod("obtenirMembre", Long.class)).isNotNull();
assertThat(MembreResource.class.getMethod("creerMembre", Membre.class)).isNotNull();
assertThat(MembreResource.class.getMethod("mettreAJourMembre", Long.class, Membre.class)).isNotNull();
assertThat(MembreResource.class.getMethod("desactiverMembre", Long.class)).isNotNull();
assertThat(MembreResource.class.getMethod("rechercherMembres", String.class)).isNotNull();
assertThat(MembreResource.class.getMethod("obtenirStatistiques")).isNotNull();
}
@Test
@DisplayName("Test de la création d'instance")
void testInstanceCreation() {
// Given & When
MembreResource resource = new MembreResource();
// Then
assertThat(resource).isNotNull();
}
@Test
@DisplayName("Test listerMembres")
void testListerMembres() {
// Given
List<Membre> membres = Arrays.asList(
createTestMembre("Jean", "Dupont"),
createTestMembre("Marie", "Martin")
);
List<MembreDTO> membresDTO = Arrays.asList(
createTestMembreDTO("Jean", "Dupont"),
createTestMembreDTO("Marie", "Martin")
);
when(membreService.listerMembresActifs(any(Page.class), any(Sort.class))).thenReturn(membres);
when(membreService.convertToDTOList(membres)).thenReturn(membresDTO);
// When
Response response = membreResource.listerMembres(0, 20, "nom", "asc");
// Then
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getEntity()).isEqualTo(membresDTO);
}
@Test
@DisplayName("Test obtenirMembre")
void testObtenirMembre() {
// Given
Long id = 1L;
Membre membre = createTestMembre("Jean", "Dupont");
when(membreService.trouverParId(id)).thenReturn(Optional.of(membre));
// When
Response response = membreResource.obtenirMembre(id);
// Then
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getEntity()).isEqualTo(membre);
}
@Test
@DisplayName("Test obtenirMembre - membre non trouvé")
void testObtenirMembreNonTrouve() {
// Given
Long id = 999L;
when(membreService.trouverParId(id)).thenReturn(Optional.empty());
// When
Response response = membreResource.obtenirMembre(id);
// Then
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
@DisplayName("Test creerMembre")
void testCreerMembre() {
// Given
MembreDTO membreDTO = createTestMembreDTO("Jean", "Dupont");
Membre membre = createTestMembre("Jean", "Dupont");
Membre membreCreated = createTestMembre("Jean", "Dupont");
membreCreated.id = 1L;
MembreDTO membreCreatedDTO = createTestMembreDTO("Jean", "Dupont");
when(membreService.convertFromDTO(any(MembreDTO.class))).thenReturn(membre);
when(membreService.creerMembre(any(Membre.class))).thenReturn(membreCreated);
when(membreService.convertToDTO(any(Membre.class))).thenReturn(membreCreatedDTO);
// When
Response response = membreResource.creerMembre(membreDTO);
// Then
assertThat(response.getStatus()).isEqualTo(201);
assertThat(response.getEntity()).isEqualTo(membreCreatedDTO);
}
@Test
@DisplayName("Test mettreAJourMembre")
void testMettreAJourMembre() {
// Given
Long id = 1L;
MembreDTO membreDTO = createTestMembreDTO("Jean", "Dupont");
Membre membre = createTestMembre("Jean", "Dupont");
Membre membreUpdated = createTestMembre("Jean", "Martin");
membreUpdated.id = id;
MembreDTO membreUpdatedDTO = createTestMembreDTO("Jean", "Martin");
when(membreService.convertFromDTO(any(MembreDTO.class))).thenReturn(membre);
when(membreService.mettreAJourMembre(anyLong(), any(Membre.class))).thenReturn(membreUpdated);
when(membreService.convertToDTO(any(Membre.class))).thenReturn(membreUpdatedDTO);
// When
Response response = membreResource.mettreAJourMembre(id, membreDTO);
// Then
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getEntity()).isEqualTo(membreUpdatedDTO);
}
@Test
@DisplayName("Test desactiverMembre")
void testDesactiverMembre() {
// Given
Long id = 1L;
// When
Response response = membreResource.desactiverMembre(id);
// Then
assertThat(response.getStatus()).isEqualTo(204);
}
@Test
@DisplayName("Test rechercherMembres")
void testRechercherMembres() {
// Given
String recherche = "Jean";
List<Membre> membres = Arrays.asList(createTestMembre("Jean", "Dupont"));
List<MembreDTO> membresDTO = Arrays.asList(createTestMembreDTO("Jean", "Dupont"));
when(membreService.rechercherMembres(anyString(), any(Page.class), any(Sort.class))).thenReturn(membres);
when(membreService.convertToDTOList(membres)).thenReturn(membresDTO);
// When
Response response = membreResource.rechercherMembres(recherche, 0, 20, "nom", "asc");
// Then
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getEntity()).isEqualTo(membresDTO);
}
@Test
@DisplayName("Test obtenirStatistiques")
void testObtenirStatistiques() {
// Given
long count = 42L;
when(membreService.compterMembresActifs()).thenReturn(count);
// When
Response response = membreResource.obtenirStatistiques();
// Then
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getEntity()).isInstanceOf(java.util.Map.class);
}
private Membre createTestMembre(String prenom, String nom) {
Membre membre = new Membre();
membre.setPrenom(prenom);
membre.setNom(nom);
membre.setEmail(prenom.toLowerCase() + "." + nom.toLowerCase() + "@test.com");
membre.setTelephone("221701234567");
membre.setDateNaissance(LocalDate.of(1990, 1, 1));
membre.setDateAdhesion(LocalDate.now());
membre.setActif(true);
membre.setNumeroMembre("UF-2025-TEST01");
return membre;
}
private MembreDTO createTestMembreDTO(String prenom, String nom) {
MembreDTO dto = new MembreDTO();
dto.setPrenom(prenom);
dto.setNom(nom);
dto.setEmail(prenom.toLowerCase() + "." + nom.toLowerCase() + "@test.com");
dto.setTelephone("221701234567");
dto.setDateNaissance(LocalDate.of(1990, 1, 1));
dto.setDateAdhesion(LocalDate.now());
dto.setStatut("ACTIF");
dto.setNumeroMembre("UF-2025-TEST01");
dto.setAssociationId(1L);
return dto;
}
}

View File

@@ -1,335 +0,0 @@
package dev.lions.unionflow.server.resource;
import dev.lions.unionflow.server.api.dto.organisation.OrganisationDTO;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.security.TestSecurity;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
/**
* Tests d'intégration pour OrganisationResource
*
* @author UnionFlow Team
* @version 1.0
* @since 2025-01-15
*/
@QuarkusTest
class OrganisationResourceTest {
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testCreerOrganisation_Success() {
OrganisationDTO organisation = createTestOrganisationDTO();
given()
.contentType(ContentType.JSON)
.body(organisation)
.when()
.post("/api/organisations")
.then()
.statusCode(201)
.body("nom", equalTo("Lions Club Test API"))
.body("email", equalTo("testapi@lionsclub.org"))
.body("actif", equalTo(true));
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testCreerOrganisation_EmailInvalide() {
OrganisationDTO organisation = createTestOrganisationDTO();
organisation.setEmail("email-invalide");
given()
.contentType(ContentType.JSON)
.body(organisation)
.when()
.post("/api/organisations")
.then()
.statusCode(400);
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testCreerOrganisation_NomVide() {
OrganisationDTO organisation = createTestOrganisationDTO();
organisation.setNom("");
given()
.contentType(ContentType.JSON)
.body(organisation)
.when()
.post("/api/organisations")
.then()
.statusCode(400);
}
@Test
void testCreerOrganisation_NonAuthentifie() {
OrganisationDTO organisation = createTestOrganisationDTO();
given()
.contentType(ContentType.JSON)
.body(organisation)
.when()
.post("/api/organisations")
.then()
.statusCode(401);
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testListerOrganisations_Success() {
given()
.when()
.get("/api/organisations")
.then()
.statusCode(200)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testListerOrganisations_AvecPagination() {
given()
.queryParam("page", 0)
.queryParam("size", 10)
.when()
.get("/api/organisations")
.then()
.statusCode(200)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testListerOrganisations_AvecRecherche() {
given()
.queryParam("recherche", "Lions")
.when()
.get("/api/organisations")
.then()
.statusCode(200)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
void testListerOrganisations_NonAuthentifie() {
given()
.when()
.get("/api/organisations")
.then()
.statusCode(401);
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testObtenirOrganisation_NonTrouvee() {
given()
.when()
.get("/api/organisations/99999")
.then()
.statusCode(404)
.body("error", equalTo("Organisation non trouvée"));
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testMettreAJourOrganisation_NonTrouvee() {
OrganisationDTO organisation = createTestOrganisationDTO();
given()
.contentType(ContentType.JSON)
.body(organisation)
.when()
.put("/api/organisations/99999")
.then()
.statusCode(404)
.body("error", containsString("Organisation non trouvée"));
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testSupprimerOrganisation_NonTrouvee() {
given()
.when()
.delete("/api/organisations/99999")
.then()
.statusCode(404)
.body("error", containsString("Organisation non trouvée"));
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testRechercheAvancee_Success() {
given()
.queryParam("nom", "Lions")
.queryParam("ville", "Abidjan")
.queryParam("page", 0)
.queryParam("size", 10)
.when()
.get("/api/organisations/recherche")
.then()
.statusCode(200)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testRechercheAvancee_SansCriteres() {
given()
.queryParam("page", 0)
.queryParam("size", 10)
.when()
.get("/api/organisations/recherche")
.then()
.statusCode(200)
.body("size()", greaterThanOrEqualTo(0));
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testActiverOrganisation_NonTrouvee() {
given()
.when()
.post("/api/organisations/99999/activer")
.then()
.statusCode(404)
.body("error", containsString("Organisation non trouvée"));
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testSuspendreOrganisation_NonTrouvee() {
given()
.when()
.post("/api/organisations/99999/suspendre")
.then()
.statusCode(404)
.body("error", containsString("Organisation non trouvée"));
}
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testObtenirStatistiques_Success() {
given()
.when()
.get("/api/organisations/statistiques")
.then()
.statusCode(200)
.body("totalOrganisations", notNullValue())
.body("organisationsActives", notNullValue())
.body("organisationsInactives", notNullValue())
.body("nouvellesOrganisations30Jours", notNullValue())
.body("tauxActivite", notNullValue())
.body("timestamp", notNullValue());
}
@Test
void testObtenirStatistiques_NonAuthentifie() {
given()
.when()
.get("/api/organisations/statistiques")
.then()
.statusCode(401);
}
/**
* Test de workflow complet : création, lecture, mise à jour, suppression
*/
@Test
@TestSecurity(user = "testUser", roles = {"ADMIN"})
void testWorkflowComplet() {
// 1. Créer une organisation
OrganisationDTO organisation = createTestOrganisationDTO();
organisation.setNom("Lions Club Workflow Test");
organisation.setEmail("workflow@lionsclub.org");
String location = given()
.contentType(ContentType.JSON)
.body(organisation)
.when()
.post("/api/organisations")
.then()
.statusCode(201)
.extract()
.header("Location");
// Extraire l'ID de l'organisation créée
String organisationId = location.substring(location.lastIndexOf("/") + 1);
// 2. Lire l'organisation créée
given()
.when()
.get("/api/organisations/" + organisationId)
.then()
.statusCode(200)
.body("nom", equalTo("Lions Club Workflow Test"))
.body("email", equalTo("workflow@lionsclub.org"));
// 3. Mettre à jour l'organisation
organisation.setDescription("Description mise à jour");
given()
.contentType(ContentType.JSON)
.body(organisation)
.when()
.put("/api/organisations/" + organisationId)
.then()
.statusCode(200)
.body("description", equalTo("Description mise à jour"));
// 4. Suspendre l'organisation
given()
.when()
.post("/api/organisations/" + organisationId + "/suspendre")
.then()
.statusCode(200);
// 5. Activer l'organisation
given()
.when()
.post("/api/organisations/" + organisationId + "/activer")
.then()
.statusCode(200);
// 6. Supprimer l'organisation (soft delete)
given()
.when()
.delete("/api/organisations/" + organisationId)
.then()
.statusCode(204);
}
/**
* Crée un DTO d'organisation pour les tests
*/
private OrganisationDTO createTestOrganisationDTO() {
OrganisationDTO dto = new OrganisationDTO();
dto.setId(UUID.randomUUID());
dto.setNom("Lions Club Test API");
dto.setNomCourt("LC Test API");
dto.setEmail("testapi@lionsclub.org");
dto.setDescription("Organisation de test pour l'API");
dto.setTelephone("+225 01 02 03 04 05");
dto.setAdresse("123 Rue de Test API");
dto.setVille("Abidjan");
dto.setCodePostal("00225");
dto.setRegion("Lagunes");
dto.setPays("Côte d'Ivoire");
dto.setSiteWeb("https://testapi.lionsclub.org");
dto.setObjectifs("Servir la communauté");
dto.setActivitesPrincipales("Actions sociales et humanitaires");
dto.setNombreMembres(0);
dto.setDateCreation(LocalDateTime.now());
dto.setActif(true);
dto.setVersion(0L);
return dto;
}
}

View File

@@ -1,332 +0,0 @@
package dev.lions.unionflow.server.service;
import dev.lions.unionflow.server.api.dto.solidarite.aide.AideDTO;
import dev.lions.unionflow.server.api.enums.solidarite.StatutAide;
import dev.lions.unionflow.server.api.enums.solidarite.TypeAide;
import dev.lions.unionflow.server.entity.Aide;
import dev.lions.unionflow.server.entity.Membre;
import dev.lions.unionflow.server.entity.Organisation;
import dev.lions.unionflow.server.repository.AideRepository;
import dev.lions.unionflow.server.repository.MembreRepository;
import dev.lions.unionflow.server.repository.OrganisationRepository;
import dev.lions.unionflow.server.security.KeycloakService;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectMock;
import jakarta.inject.Inject;
import jakarta.ws.rs.NotFoundException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/**
* Tests unitaires pour AideService
*
* @author UnionFlow Team
* @version 1.0
* @since 2025-01-15
*/
@QuarkusTest
@DisplayName("AideService - Tests unitaires")
class AideServiceTest {
@Inject
AideService aideService;
@InjectMock
AideRepository aideRepository;
@InjectMock
MembreRepository membreRepository;
@InjectMock
OrganisationRepository organisationRepository;
@InjectMock
KeycloakService keycloakService;
private Membre membreTest;
private Organisation organisationTest;
private Aide aideTest;
private AideDTO aideDTOTest;
@BeforeEach
void setUp() {
// Membre de test
membreTest = new Membre();
membreTest.id = 1L;
membreTest.setNumeroMembre("UF-2025-TEST001");
membreTest.setNom("Dupont");
membreTest.setPrenom("Jean");
membreTest.setEmail("jean.dupont@test.com");
membreTest.setActif(true);
// Organisation de test
organisationTest = new Organisation();
organisationTest.id = 1L;
organisationTest.setNom("Lions Club Test");
organisationTest.setEmail("contact@lionstest.com");
organisationTest.setActif(true);
// Aide de test
aideTest = new Aide();
aideTest.id = 1L;
aideTest.setNumeroReference("AIDE-2025-TEST01");
aideTest.setTitre("Aide médicale urgente");
aideTest.setDescription("Demande d'aide pour frais médicaux urgents");
aideTest.setTypeAide(TypeAide.AIDE_MEDICALE);
aideTest.setMontantDemande(new BigDecimal("500000.00"));
aideTest.setStatut(StatutAide.EN_ATTENTE);
aideTest.setPriorite("URGENTE");
aideTest.setMembreDemandeur(membreTest);
aideTest.setOrganisation(organisationTest);
aideTest.setActif(true);
aideTest.setDateCreation(LocalDateTime.now());
// DTO de test
aideDTOTest = new AideDTO();
aideDTOTest.setId(UUID.randomUUID());
aideDTOTest.setNumeroReference("AIDE-2025-TEST01");
aideDTOTest.setTitre("Aide médicale urgente");
aideDTOTest.setDescription("Demande d'aide pour frais médicaux urgents");
aideDTOTest.setTypeAide("MEDICALE");
aideDTOTest.setMontantDemande(new BigDecimal("500000.00"));
aideDTOTest.setStatut("EN_ATTENTE");
aideDTOTest.setPriorite("URGENTE");
aideDTOTest.setMembreDemandeurId(UUID.randomUUID());
aideDTOTest.setAssociationId(UUID.randomUUID());
aideDTOTest.setActif(true);
}
@Nested
@DisplayName("Tests de création d'aide")
class CreationAideTests {
@Test
@DisplayName("Création d'aide réussie")
void testCreerAide_Success() {
// Given
when(membreRepository.findByIdOptional(anyLong())).thenReturn(Optional.of(membreTest));
when(organisationRepository.findByIdOptional(anyLong())).thenReturn(Optional.of(organisationTest));
when(keycloakService.getCurrentUserEmail()).thenReturn("admin@test.com");
ArgumentCaptor<Aide> aideCaptor = ArgumentCaptor.forClass(Aide.class);
doNothing().when(aideRepository).persist(aideCaptor.capture());
// When
AideDTO result = aideService.creerAide(aideDTOTest);
// Then
assertThat(result).isNotNull();
assertThat(result.getTitre()).isEqualTo(aideDTOTest.getTitre());
assertThat(result.getDescription()).isEqualTo(aideDTOTest.getDescription());
Aide aidePersistee = aideCaptor.getValue();
assertThat(aidePersistee.getTitre()).isEqualTo(aideDTOTest.getTitre());
assertThat(aidePersistee.getMembreDemandeur()).isEqualTo(membreTest);
assertThat(aidePersistee.getOrganisation()).isEqualTo(organisationTest);
assertThat(aidePersistee.getCreePar()).isEqualTo("admin@test.com");
verify(aideRepository).persist(any(Aide.class));
}
@Test
@DisplayName("Création d'aide - Membre non trouvé")
void testCreerAide_MembreNonTrouve() {
// Given
when(membreRepository.findByIdOptional(anyLong())).thenReturn(Optional.empty());
// When & Then
assertThatThrownBy(() -> aideService.creerAide(aideDTOTest))
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Membre demandeur non trouvé");
verify(aideRepository, never()).persist(any(Aide.class));
}
@Test
@DisplayName("Création d'aide - Organisation non trouvée")
void testCreerAide_OrganisationNonTrouvee() {
// Given
when(membreRepository.findByIdOptional(anyLong())).thenReturn(Optional.of(membreTest));
when(organisationRepository.findByIdOptional(anyLong())).thenReturn(Optional.empty());
// When & Then
assertThatThrownBy(() -> aideService.creerAide(aideDTOTest))
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Organisation non trouvée");
verify(aideRepository, never()).persist(any(Aide.class));
}
@Test
@DisplayName("Création d'aide - Montant invalide")
void testCreerAide_MontantInvalide() {
// Given
aideDTOTest.setMontantDemande(new BigDecimal("-100.00"));
when(membreRepository.findByIdOptional(anyLong())).thenReturn(Optional.of(membreTest));
when(organisationRepository.findByIdOptional(anyLong())).thenReturn(Optional.of(organisationTest));
// When & Then
assertThatThrownBy(() -> aideService.creerAide(aideDTOTest))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Le montant demandé doit être positif");
verify(aideRepository, never()).persist(any(Aide.class));
}
}
@Nested
@DisplayName("Tests de récupération d'aide")
class RecuperationAideTests {
@Test
@DisplayName("Récupération d'aide par ID réussie")
void testObtenirAideParId_Success() {
// Given
when(aideRepository.findByIdOptional(1L)).thenReturn(Optional.of(aideTest));
when(keycloakService.getCurrentUserEmail()).thenReturn("autre@test.com");
// When
AideDTO result = aideService.obtenirAideParId(1L);
// Then
assertThat(result).isNotNull();
assertThat(result.getTitre()).isEqualTo(aideTest.getTitre());
assertThat(result.getDescription()).isEqualTo(aideTest.getDescription());
assertThat(result.getStatut()).isEqualTo(aideTest.getStatut().name());
}
@Test
@DisplayName("Récupération d'aide par ID - Non trouvée")
void testObtenirAideParId_NonTrouvee() {
// Given
when(aideRepository.findByIdOptional(999L)).thenReturn(Optional.empty());
// When & Then
assertThatThrownBy(() -> aideService.obtenirAideParId(999L))
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Demande d'aide non trouvée");
}
@Test
@DisplayName("Récupération d'aide par référence réussie")
void testObtenirAideParReference_Success() {
// Given
String reference = "AIDE-2025-TEST01";
when(aideRepository.findByNumeroReference(reference)).thenReturn(Optional.of(aideTest));
when(keycloakService.getCurrentUserEmail()).thenReturn("autre@test.com");
// When
AideDTO result = aideService.obtenirAideParReference(reference);
// Then
assertThat(result).isNotNull();
assertThat(result.getNumeroReference()).isEqualTo(reference);
}
}
@Nested
@DisplayName("Tests de mise à jour d'aide")
class MiseAJourAideTests {
@Test
@DisplayName("Mise à jour d'aide réussie")
void testMettreAJourAide_Success() {
// Given
when(aideRepository.findByIdOptional(1L)).thenReturn(Optional.of(aideTest));
when(keycloakService.getCurrentUserEmail()).thenReturn("jean.dupont@test.com");
when(keycloakService.hasRole("admin")).thenReturn(false);
when(keycloakService.hasRole("gestionnaire_aide")).thenReturn(false);
AideDTO aideMiseAJour = new AideDTO();
aideMiseAJour.setTitre("Titre modifié");
aideMiseAJour.setDescription("Description modifiée");
aideMiseAJour.setMontantDemande(new BigDecimal("600000.00"));
aideMiseAJour.setPriorite("HAUTE");
// When
AideDTO result = aideService.mettreAJourAide(1L, aideMiseAJour);
// Then
assertThat(result).isNotNull();
assertThat(aideTest.getTitre()).isEqualTo("Titre modifié");
assertThat(aideTest.getDescription()).isEqualTo("Description modifiée");
assertThat(aideTest.getMontantDemande()).isEqualTo(new BigDecimal("600000.00"));
assertThat(aideTest.getPriorite()).isEqualTo("HAUTE");
}
@Test
@DisplayName("Mise à jour d'aide - Accès non autorisé")
void testMettreAJourAide_AccesNonAutorise() {
// Given
when(aideRepository.findByIdOptional(1L)).thenReturn(Optional.of(aideTest));
when(keycloakService.getCurrentUserEmail()).thenReturn("autre@test.com");
when(keycloakService.hasRole("admin")).thenReturn(false);
when(keycloakService.hasRole("gestionnaire_aide")).thenReturn(false);
AideDTO aideMiseAJour = new AideDTO();
aideMiseAJour.setTitre("Titre modifié");
// When & Then
assertThatThrownBy(() -> aideService.mettreAJourAide(1L, aideMiseAJour))
.isInstanceOf(SecurityException.class)
.hasMessageContaining("Vous n'avez pas les permissions");
}
}
@Nested
@DisplayName("Tests de conversion DTO/Entity")
class ConversionTests {
@Test
@DisplayName("Conversion Entity vers DTO")
void testConvertToDTO() {
// When
AideDTO result = aideService.convertToDTO(aideTest);
// Then
assertThat(result).isNotNull();
assertThat(result.getTitre()).isEqualTo(aideTest.getTitre());
assertThat(result.getDescription()).isEqualTo(aideTest.getDescription());
assertThat(result.getMontantDemande()).isEqualTo(aideTest.getMontantDemande());
assertThat(result.getStatut()).isEqualTo(aideTest.getStatut().name());
assertThat(result.getTypeAide()).isEqualTo(aideTest.getTypeAide().name());
}
@Test
@DisplayName("Conversion DTO vers Entity")
void testConvertFromDTO() {
// When
Aide result = aideService.convertFromDTO(aideDTOTest);
// Then
assertThat(result).isNotNull();
assertThat(result.getTitre()).isEqualTo(aideDTOTest.getTitre());
assertThat(result.getDescription()).isEqualTo(aideDTOTest.getDescription());
assertThat(result.getMontantDemande()).isEqualTo(aideDTOTest.getMontantDemande());
assertThat(result.getStatut()).isEqualTo(StatutAide.EN_ATTENTE);
assertThat(result.getTypeAide()).isEqualTo(TypeAide.AIDE_MEDICALE);
}
@Test
@DisplayName("Conversion DTO null")
void testConvertFromDTO_Null() {
// When
Aide result = aideService.convertFromDTO(null);
// Then
assertThat(result).isNull();
}
}
}

View File

@@ -1,408 +0,0 @@
package dev.lions.unionflow.server.service;
import dev.lions.unionflow.server.entity.Evenement;
import dev.lions.unionflow.server.entity.Evenement.StatutEvenement;
import dev.lions.unionflow.server.entity.Evenement.TypeEvenement;
import dev.lions.unionflow.server.entity.Membre;
import dev.lions.unionflow.server.entity.Organisation;
import dev.lions.unionflow.server.repository.EvenementRepository;
import dev.lions.unionflow.server.repository.MembreRepository;
import dev.lions.unionflow.server.repository.OrganisationRepository;
import io.quarkus.panache.common.Page;
import io.quarkus.panache.common.Sort;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectMock;
import jakarta.inject.Inject;
import org.junit.jupiter.api.*;
import org.mockito.Mockito;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/**
* Tests unitaires pour EvenementService
*
* Tests complets du service de gestion des événements avec
* validation des règles métier et intégration Keycloak.
*
* @author UnionFlow Team
* @version 1.0
* @since 2025-01-15
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@DisplayName("Tests unitaires - Service Événements")
class EvenementServiceTest {
@Inject
EvenementService evenementService;
@InjectMock
EvenementRepository evenementRepository;
@InjectMock
MembreRepository membreRepository;
@InjectMock
OrganisationRepository organisationRepository;
@InjectMock
KeycloakService keycloakService;
private Evenement evenementTest;
private Organisation organisationTest;
private Membre membreTest;
@BeforeEach
void setUp() {
// Données de test
organisationTest = Organisation.builder()
.nom("Union Test")
.typeOrganisation("ASSOCIATION")
.statut("ACTIVE")
.email("test@union.com")
.actif(true)
.build();
organisationTest.id = 1L;
membreTest = Membre.builder()
.numeroMembre("UF2025-TEST01")
.prenom("Jean")
.nom("Dupont")
.email("jean.dupont@test.com")
.actif(true)
.build();
membreTest.id = 1L;
evenementTest = Evenement.builder()
.titre("Assemblée Générale 2025")
.description("Assemblée générale annuelle de l'union")
.dateDebut(LocalDateTime.now().plusDays(30))
.dateFin(LocalDateTime.now().plusDays(30).plusHours(3))
.lieu("Salle de conférence")
.typeEvenement(TypeEvenement.ASSEMBLEE_GENERALE)
.statut(StatutEvenement.PLANIFIE)
.capaciteMax(100)
.prix(BigDecimal.valueOf(25.00))
.inscriptionRequise(true)
.visiblePublic(true)
.actif(true)
.organisation(organisationTest)
.organisateur(membreTest)
.build();
evenementTest.id = 1L;
}
@Test
@Order(1)
@DisplayName("Création d'événement - Succès")
void testCreerEvenement_Succes() {
// Given
when(keycloakService.getCurrentUserEmail()).thenReturn("jean.dupont@test.com");
when(evenementRepository.findByTitre(anyString())).thenReturn(Optional.empty());
doNothing().when(evenementRepository).persist(any(Evenement.class));
// When
Evenement resultat = evenementService.creerEvenement(evenementTest);
// Then
assertNotNull(resultat);
assertEquals("Assemblée Générale 2025", resultat.getTitre());
assertEquals(StatutEvenement.PLANIFIE, resultat.getStatut());
assertTrue(resultat.getActif());
assertEquals("jean.dupont@test.com", resultat.getCreePar());
verify(evenementRepository).persist(any(Evenement.class));
}
@Test
@Order(2)
@DisplayName("Création d'événement - Titre obligatoire")
void testCreerEvenement_TitreObligatoire() {
// Given
evenementTest.setTitre(null);
// When & Then
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> evenementService.creerEvenement(evenementTest)
);
assertEquals("Le titre de l'événement est obligatoire", exception.getMessage());
verify(evenementRepository, never()).persist(any(Evenement.class));
}
@Test
@Order(3)
@DisplayName("Création d'événement - Date de début obligatoire")
void testCreerEvenement_DateDebutObligatoire() {
// Given
evenementTest.setDateDebut(null);
// When & Then
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> evenementService.creerEvenement(evenementTest)
);
assertEquals("La date de début est obligatoire", exception.getMessage());
}
@Test
@Order(4)
@DisplayName("Création d'événement - Date de début dans le passé")
void testCreerEvenement_DateDebutPassee() {
// Given
evenementTest.setDateDebut(LocalDateTime.now().minusDays(1));
// When & Then
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> evenementService.creerEvenement(evenementTest)
);
assertEquals("La date de début ne peut pas être dans le passé", exception.getMessage());
}
@Test
@Order(5)
@DisplayName("Création d'événement - Date de fin antérieure à date de début")
void testCreerEvenement_DateFinInvalide() {
// Given
evenementTest.setDateFin(evenementTest.getDateDebut().minusHours(1));
// When & Then
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> evenementService.creerEvenement(evenementTest)
);
assertEquals("La date de fin ne peut pas être antérieure à la date de début", exception.getMessage());
}
@Test
@Order(6)
@DisplayName("Mise à jour d'événement - Succès")
void testMettreAJourEvenement_Succes() {
// Given
when(evenementRepository.findByIdOptional(1L)).thenReturn(Optional.of(evenementTest));
when(keycloakService.hasRole("ADMIN")).thenReturn(true);
when(keycloakService.getCurrentUserEmail()).thenReturn("admin@test.com");
doNothing().when(evenementRepository).persist(any(Evenement.class));
Evenement evenementMisAJour = Evenement.builder()
.titre("Assemblée Générale 2025 - Modifiée")
.description("Description mise à jour")
.dateDebut(LocalDateTime.now().plusDays(35))
.dateFin(LocalDateTime.now().plusDays(35).plusHours(4))
.lieu("Nouvelle salle")
.typeEvenement(TypeEvenement.ASSEMBLEE_GENERALE)
.capaciteMax(150)
.prix(BigDecimal.valueOf(30.00))
.inscriptionRequise(true)
.visiblePublic(true)
.build();
// When
Evenement resultat = evenementService.mettreAJourEvenement(1L, evenementMisAJour);
// Then
assertNotNull(resultat);
assertEquals("Assemblée Générale 2025 - Modifiée", resultat.getTitre());
assertEquals("Description mise à jour", resultat.getDescription());
assertEquals("Nouvelle salle", resultat.getLieu());
assertEquals(150, resultat.getCapaciteMax());
assertEquals(BigDecimal.valueOf(30.00), resultat.getPrix());
assertEquals("admin@test.com", resultat.getModifiePar());
verify(evenementRepository).persist(any(Evenement.class));
}
@Test
@Order(7)
@DisplayName("Mise à jour d'événement - Événement non trouvé")
void testMettreAJourEvenement_NonTrouve() {
// Given
when(evenementRepository.findByIdOptional(999L)).thenReturn(Optional.empty());
// When & Then
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> evenementService.mettreAJourEvenement(999L, evenementTest)
);
assertEquals("Événement non trouvé avec l'ID: 999", exception.getMessage());
}
@Test
@Order(8)
@DisplayName("Suppression d'événement - Succès")
void testSupprimerEvenement_Succes() {
// Given
when(evenementRepository.findByIdOptional(1L)).thenReturn(Optional.of(evenementTest));
when(keycloakService.hasRole("ADMIN")).thenReturn(true);
when(keycloakService.getCurrentUserEmail()).thenReturn("admin@test.com");
when(evenementTest.getNombreInscrits()).thenReturn(0);
doNothing().when(evenementRepository).persist(any(Evenement.class));
// When
assertDoesNotThrow(() -> evenementService.supprimerEvenement(1L));
// Then
assertFalse(evenementTest.getActif());
assertEquals("admin@test.com", evenementTest.getModifiePar());
verify(evenementRepository).persist(any(Evenement.class));
}
@Test
@Order(9)
@DisplayName("Recherche d'événements - Succès")
void testRechercherEvenements_Succes() {
// Given
List<Evenement> evenementsAttendus = List.of(evenementTest);
when(evenementRepository.findByTitreOrDescription(anyString(), any(Page.class), any(Sort.class)))
.thenReturn(evenementsAttendus);
// When
List<Evenement> resultat = evenementService.rechercherEvenements(
"Assemblée", Page.of(0, 10), Sort.by("dateDebut"));
// Then
assertNotNull(resultat);
assertEquals(1, resultat.size());
assertEquals("Assemblée Générale 2025", resultat.get(0).getTitre());
verify(evenementRepository).findByTitreOrDescription(eq("Assemblée"), any(Page.class), any(Sort.class));
}
@Test
@Order(10)
@DisplayName("Changement de statut - Succès")
void testChangerStatut_Succes() {
// Given
when(evenementRepository.findByIdOptional(1L)).thenReturn(Optional.of(evenementTest));
when(keycloakService.hasRole("ADMIN")).thenReturn(true);
when(keycloakService.getCurrentUserEmail()).thenReturn("admin@test.com");
doNothing().when(evenementRepository).persist(any(Evenement.class));
// When
Evenement resultat = evenementService.changerStatut(1L, StatutEvenement.CONFIRME);
// Then
assertNotNull(resultat);
assertEquals(StatutEvenement.CONFIRME, resultat.getStatut());
assertEquals("admin@test.com", resultat.getModifiePar());
verify(evenementRepository).persist(any(Evenement.class));
}
@Test
@Order(11)
@DisplayName("Statistiques des événements")
void testObtenirStatistiques() {
// Given
Map<String, Long> statsBase = Map.of(
"total", 100L,
"actifs", 80L,
"aVenir", 30L,
"enCours", 5L,
"passes", 45L,
"publics", 70L,
"avecInscription", 25L
);
when(evenementRepository.getStatistiques()).thenReturn(statsBase);
// When
Map<String, Object> resultat = evenementService.obtenirStatistiques();
// Then
assertNotNull(resultat);
assertEquals(100L, resultat.get("total"));
assertEquals(80L, resultat.get("actifs"));
assertEquals(30L, resultat.get("aVenir"));
assertEquals(80.0, resultat.get("tauxActivite"));
assertEquals(37.5, resultat.get("tauxEvenementsAVenir"));
assertEquals(6.25, resultat.get("tauxEvenementsEnCours"));
assertNotNull(resultat.get("timestamp"));
verify(evenementRepository).getStatistiques();
}
@Test
@Order(12)
@DisplayName("Lister événements actifs avec pagination")
void testListerEvenementsActifs() {
// Given
List<Evenement> evenementsAttendus = List.of(evenementTest);
when(evenementRepository.findAllActifs(any(Page.class), any(Sort.class)))
.thenReturn(evenementsAttendus);
// When
List<Evenement> resultat = evenementService.listerEvenementsActifs(
Page.of(0, 20), Sort.by("dateDebut"));
// Then
assertNotNull(resultat);
assertEquals(1, resultat.size());
assertEquals("Assemblée Générale 2025", resultat.get(0).getTitre());
verify(evenementRepository).findAllActifs(any(Page.class), any(Sort.class));
}
@Test
@Order(13)
@DisplayName("Validation des règles métier - Prix négatif")
void testValidation_PrixNegatif() {
// Given
evenementTest.setPrix(BigDecimal.valueOf(-10.00));
// When & Then
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> evenementService.creerEvenement(evenementTest)
);
assertEquals("Le prix ne peut pas être négatif", exception.getMessage());
}
@Test
@Order(14)
@DisplayName("Validation des règles métier - Capacité négative")
void testValidation_CapaciteNegative() {
// Given
evenementTest.setCapaciteMax(-5);
// When & Then
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> evenementService.creerEvenement(evenementTest)
);
assertEquals("La capacité maximale ne peut pas être négative", exception.getMessage());
}
@Test
@Order(15)
@DisplayName("Permissions - Utilisateur non autorisé")
void testPermissions_UtilisateurNonAutorise() {
// Given
when(evenementRepository.findByIdOptional(1L)).thenReturn(Optional.of(evenementTest));
when(keycloakService.hasRole(anyString())).thenReturn(false);
when(keycloakService.getCurrentUserEmail()).thenReturn("autre@test.com");
// When & Then
SecurityException exception = assertThrows(
SecurityException.class,
() -> evenementService.mettreAJourEvenement(1L, evenementTest)
);
assertEquals("Vous n'avez pas les permissions pour modifier cet événement", exception.getMessage());
}
}

View File

@@ -1,350 +0,0 @@
package dev.lions.unionflow.server.service;
import dev.lions.unionflow.server.entity.Membre;
import dev.lions.unionflow.server.repository.MembreRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
/**
* Tests pour MembreService
*
* @author Lions Dev Team
* @since 2025-01-10
*/
@ExtendWith(MockitoExtension.class)
@DisplayName("Tests MembreService")
class MembreServiceTest {
@InjectMocks
MembreService membreService;
@Mock
MembreRepository membreRepository;
private Membre membreTest;
@BeforeEach
void setUp() {
membreTest = Membre.builder()
.prenom("Jean")
.nom("Dupont")
.email("jean.dupont@test.com")
.telephone("221701234567")
.dateNaissance(LocalDate.of(1990, 5, 15))
.dateAdhesion(LocalDate.now())
.actif(true)
.build();
}
@Nested
@DisplayName("Tests creerMembre")
class CreerMembreTests {
@Test
@DisplayName("Création réussie d'un membre")
void testCreerMembreReussi() {
// Given
when(membreRepository.findByEmail(anyString())).thenReturn(Optional.empty());
when(membreRepository.findByNumeroMembre(anyString())).thenReturn(Optional.empty());
// When
Membre result = membreService.creerMembre(membreTest);
// Then
assertThat(result).isNotNull();
assertThat(result.getNumeroMembre()).isNotNull();
assertThat(result.getNumeroMembre()).startsWith("UF2025-");
verify(membreRepository).persist(membreTest);
}
@Test
@DisplayName("Erreur si email déjà existant")
void testCreerMembreEmailExistant() {
// Given
when(membreRepository.findByEmail(membreTest.getEmail()))
.thenReturn(Optional.of(membreTest));
// When & Then
assertThatThrownBy(() -> membreService.creerMembre(membreTest))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Un membre avec cet email existe déjà");
}
@Test
@DisplayName("Erreur si numéro de membre déjà existant")
void testCreerMembreNumeroExistant() {
// Given
membreTest.setNumeroMembre("UF2025-EXIST");
when(membreRepository.findByEmail(anyString())).thenReturn(Optional.empty());
when(membreRepository.findByNumeroMembre("UF2025-EXIST"))
.thenReturn(Optional.of(membreTest));
// When & Then
assertThatThrownBy(() -> membreService.creerMembre(membreTest))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Un membre avec ce numéro existe déjà");
}
@Test
@DisplayName("Génération automatique du numéro de membre")
void testGenerationNumeroMembre() {
// Given
membreTest.setNumeroMembre(null);
when(membreRepository.findByEmail(anyString())).thenReturn(Optional.empty());
when(membreRepository.findByNumeroMembre(anyString())).thenReturn(Optional.empty());
// When
membreService.creerMembre(membreTest);
// Then
ArgumentCaptor<Membre> captor = ArgumentCaptor.forClass(Membre.class);
verify(membreRepository).persist(captor.capture());
assertThat(captor.getValue().getNumeroMembre()).isNotNull();
assertThat(captor.getValue().getNumeroMembre()).startsWith("UF2025-");
}
@Test
@DisplayName("Génération automatique du numéro de membre avec chaîne vide")
void testGenerationNumeroMembreChainVide() {
// Given
membreTest.setNumeroMembre(""); // Chaîne vide
when(membreRepository.findByEmail(anyString())).thenReturn(Optional.empty());
when(membreRepository.findByNumeroMembre(anyString())).thenReturn(Optional.empty());
// When
membreService.creerMembre(membreTest);
// Then
ArgumentCaptor<Membre> captor = ArgumentCaptor.forClass(Membre.class);
verify(membreRepository).persist(captor.capture());
assertThat(captor.getValue().getNumeroMembre()).isNotNull();
assertThat(captor.getValue().getNumeroMembre()).isNotEmpty();
assertThat(captor.getValue().getNumeroMembre()).startsWith("UF2025-");
}
}
@Nested
@DisplayName("Tests mettreAJourMembre")
class MettreAJourMembreTests {
@Test
@DisplayName("Mise à jour réussie d'un membre")
void testMettreAJourMembreReussi() {
// Given
Long id = 1L;
membreTest.id = id; // Utiliser le champ directement
Membre membreModifie = Membre.builder()
.prenom("Pierre")
.nom("Martin")
.email("pierre.martin@test.com")
.telephone("221701234568")
.dateNaissance(LocalDate.of(1985, 8, 20))
.actif(false)
.build();
when(membreRepository.findById(id)).thenReturn(membreTest);
when(membreRepository.findByEmail("pierre.martin@test.com")).thenReturn(Optional.empty());
// When
Membre result = membreService.mettreAJourMembre(id, membreModifie);
// Then
assertThat(result.getPrenom()).isEqualTo("Pierre");
assertThat(result.getNom()).isEqualTo("Martin");
assertThat(result.getEmail()).isEqualTo("pierre.martin@test.com");
assertThat(result.getTelephone()).isEqualTo("221701234568");
assertThat(result.getDateNaissance()).isEqualTo(LocalDate.of(1985, 8, 20));
assertThat(result.getActif()).isFalse();
}
@Test
@DisplayName("Erreur si membre non trouvé")
void testMettreAJourMembreNonTrouve() {
// Given
Long id = 999L;
when(membreRepository.findById(id)).thenReturn(null);
// When & Then
assertThatThrownBy(() -> membreService.mettreAJourMembre(id, membreTest))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Membre non trouvé avec l'ID: " + id);
}
@Test
@DisplayName("Erreur si nouvel email déjà existant")
void testMettreAJourMembreEmailExistant() {
// Given
Long id = 1L;
membreTest.id = id; // Utiliser le champ directement
membreTest.setEmail("ancien@test.com");
Membre membreModifie = Membre.builder()
.email("nouveau@test.com")
.build();
Membre autreMembreAvecEmail = Membre.builder()
.email("nouveau@test.com")
.build();
autreMembreAvecEmail.id = 2L; // Utiliser le champ directement
when(membreRepository.findById(id)).thenReturn(membreTest);
when(membreRepository.findByEmail("nouveau@test.com"))
.thenReturn(Optional.of(autreMembreAvecEmail));
// When & Then
assertThatThrownBy(() -> membreService.mettreAJourMembre(id, membreModifie))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Un membre avec cet email existe déjà");
}
@Test
@DisplayName("Mise à jour sans changement d'email")
void testMettreAJourMembreSansChangementEmail() {
// Given
Long id = 1L;
membreTest.id = id; // Utiliser le champ directement
membreTest.setEmail("meme@test.com");
Membre membreModifie = Membre.builder()
.prenom("Pierre")
.nom("Martin")
.email("meme@test.com") // Même email
.telephone("221701234568")
.dateNaissance(LocalDate.of(1985, 8, 20))
.actif(false)
.build();
when(membreRepository.findById(id)).thenReturn(membreTest);
// Pas besoin de mocker findByEmail car l'email n'a pas changé
// When
Membre result = membreService.mettreAJourMembre(id, membreModifie);
// Then
assertThat(result.getPrenom()).isEqualTo("Pierre");
assertThat(result.getNom()).isEqualTo("Martin");
assertThat(result.getEmail()).isEqualTo("meme@test.com");
// Vérifier que findByEmail n'a pas été appelé
verify(membreRepository, never()).findByEmail("meme@test.com");
}
}
@Test
@DisplayName("Test trouverParId")
void testTrouverParId() {
// Given
Long id = 1L;
when(membreRepository.findById(id)).thenReturn(membreTest);
// When
Optional<Membre> result = membreService.trouverParId(id);
// Then
assertThat(result).isPresent();
assertThat(result.get()).isEqualTo(membreTest);
}
@Test
@DisplayName("Test trouverParEmail")
void testTrouverParEmail() {
// Given
String email = "jean.dupont@test.com";
when(membreRepository.findByEmail(email)).thenReturn(Optional.of(membreTest));
// When
Optional<Membre> result = membreService.trouverParEmail(email);
// Then
assertThat(result).isPresent();
assertThat(result.get()).isEqualTo(membreTest);
}
@Test
@DisplayName("Test listerMembresActifs")
void testListerMembresActifs() {
// Given
List<Membre> membresActifs = Arrays.asList(membreTest);
when(membreRepository.findAllActifs()).thenReturn(membresActifs);
// When
List<Membre> result = membreService.listerMembresActifs();
// Then
assertThat(result).hasSize(1);
assertThat(result.get(0)).isEqualTo(membreTest);
}
@Test
@DisplayName("Test rechercherMembres")
void testRechercherMembres() {
// Given
String recherche = "Jean";
List<Membre> resultatsRecherche = Arrays.asList(membreTest);
when(membreRepository.findByNomOrPrenom(recherche)).thenReturn(resultatsRecherche);
// When
List<Membre> result = membreService.rechercherMembres(recherche);
// Then
assertThat(result).hasSize(1);
assertThat(result.get(0)).isEqualTo(membreTest);
}
@Test
@DisplayName("Test desactiverMembre - Succès")
void testDesactiverMembreReussi() {
// Given
Long id = 1L;
membreTest.id = id; // Utiliser le champ directement
when(membreRepository.findById(id)).thenReturn(membreTest);
// When
membreService.desactiverMembre(id);
// Then
assertThat(membreTest.getActif()).isFalse();
}
@Test
@DisplayName("Test desactiverMembre - Membre non trouvé")
void testDesactiverMembreNonTrouve() {
// Given
Long id = 999L;
when(membreRepository.findById(id)).thenReturn(null);
// When & Then
assertThatThrownBy(() -> membreService.desactiverMembre(id))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Membre non trouvé avec l'ID: " + id);
}
@Test
@DisplayName("Test compterMembresActifs")
void testCompterMembresActifs() {
// Given
when(membreRepository.countActifs()).thenReturn(5L);
// When
long result = membreService.compterMembresActifs();
// Then
assertThat(result).isEqualTo(5L);
}
}

View File

@@ -1,346 +0,0 @@
package dev.lions.unionflow.server.service;
import dev.lions.unionflow.server.entity.Organisation;
import dev.lions.unionflow.server.repository.OrganisationRepository;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectMock;
import jakarta.inject.Inject;
import jakarta.ws.rs.NotFoundException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/**
* Tests unitaires pour OrganisationService
*
* @author UnionFlow Team
* @version 1.0
* @since 2025-01-15
*/
@QuarkusTest
class OrganisationServiceTest {
@Inject
OrganisationService organisationService;
@InjectMock
OrganisationRepository organisationRepository;
private Organisation organisationTest;
@BeforeEach
void setUp() {
organisationTest = Organisation.builder()
.nom("Lions Club Test")
.nomCourt("LC Test")
.email("test@lionsclub.org")
.typeOrganisation("LIONS_CLUB")
.statut("ACTIVE")
.description("Organisation de test")
.telephone("+225 01 02 03 04 05")
.adresse("123 Rue de Test")
.ville("Abidjan")
.region("Lagunes")
.pays("Côte d'Ivoire")
.nombreMembres(25)
.actif(true)
.dateCreation(LocalDateTime.now())
.version(0L)
.build();
organisationTest.id = 1L;
}
@Test
void testCreerOrganisation_Success() {
// Given
Organisation organisationToCreate = Organisation.builder()
.nom("Lions Club Test New")
.email("testnew@lionsclub.org")
.typeOrganisation("LIONS_CLUB")
.build();
when(organisationRepository.findByEmail("testnew@lionsclub.org")).thenReturn(Optional.empty());
when(organisationRepository.findByNom("Lions Club Test New")).thenReturn(Optional.empty());
// When
Organisation result = organisationService.creerOrganisation(organisationToCreate);
// Then
assertNotNull(result);
assertEquals("Lions Club Test New", result.getNom());
assertEquals("ACTIVE", result.getStatut());
verify(organisationRepository).findByEmail("testnew@lionsclub.org");
verify(organisationRepository).findByNom("Lions Club Test New");
}
@Test
void testCreerOrganisation_EmailDejaExistant() {
// Given
when(organisationRepository.findByEmail(anyString())).thenReturn(Optional.of(organisationTest));
// When & Then
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> organisationService.creerOrganisation(organisationTest));
assertEquals("Une organisation avec cet email existe déjà", exception.getMessage());
verify(organisationRepository).findByEmail("test@lionsclub.org");
verify(organisationRepository, never()).findByNom(anyString());
}
@Test
void testCreerOrganisation_NomDejaExistant() {
// Given
when(organisationRepository.findByEmail(anyString())).thenReturn(Optional.empty());
when(organisationRepository.findByNom(anyString())).thenReturn(Optional.of(organisationTest));
// When & Then
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> organisationService.creerOrganisation(organisationTest));
assertEquals("Une organisation avec ce nom existe déjà", exception.getMessage());
verify(organisationRepository).findByEmail("test@lionsclub.org");
verify(organisationRepository).findByNom("Lions Club Test");
}
@Test
void testMettreAJourOrganisation_Success() {
// Given
Organisation organisationMiseAJour = Organisation.builder()
.nom("Lions Club Test Modifié")
.email("test@lionsclub.org")
.description("Description modifiée")
.telephone("+225 01 02 03 04 06")
.build();
when(organisationRepository.findByIdOptional(1L)).thenReturn(Optional.of(organisationTest));
when(organisationRepository.findByNom("Lions Club Test Modifié")).thenReturn(Optional.empty());
// When
Organisation result = organisationService.mettreAJourOrganisation(1L, organisationMiseAJour, "testUser");
// Then
assertNotNull(result);
assertEquals("Lions Club Test Modifié", result.getNom());
assertEquals("Description modifiée", result.getDescription());
assertEquals("+225 01 02 03 04 06", result.getTelephone());
assertEquals("testUser", result.getModifiePar());
assertNotNull(result.getDateModification());
assertEquals(1L, result.getVersion());
}
@Test
void testMettreAJourOrganisation_OrganisationNonTrouvee() {
// Given
when(organisationRepository.findByIdOptional(1L)).thenReturn(Optional.empty());
// When & Then
NotFoundException exception = assertThrows(NotFoundException.class,
() -> organisationService.mettreAJourOrganisation(1L, organisationTest, "testUser"));
assertEquals("Organisation non trouvée avec l'ID: 1", exception.getMessage());
}
@Test
void testSupprimerOrganisation_Success() {
// Given
organisationTest.setNombreMembres(0);
when(organisationRepository.findByIdOptional(1L)).thenReturn(Optional.of(organisationTest));
// When
organisationService.supprimerOrganisation(1L, "testUser");
// Then
assertFalse(organisationTest.getActif());
assertEquals("DISSOUTE", organisationTest.getStatut());
assertEquals("testUser", organisationTest.getModifiePar());
assertNotNull(organisationTest.getDateModification());
}
@Test
void testSupprimerOrganisation_AvecMembresActifs() {
// Given
organisationTest.setNombreMembres(5);
when(organisationRepository.findByIdOptional(1L)).thenReturn(Optional.of(organisationTest));
// When & Then
IllegalStateException exception = assertThrows(IllegalStateException.class,
() -> organisationService.supprimerOrganisation(1L, "testUser"));
assertEquals("Impossible de supprimer une organisation avec des membres actifs", exception.getMessage());
}
@Test
void testTrouverParId_Success() {
// Given
when(organisationRepository.findByIdOptional(1L)).thenReturn(Optional.of(organisationTest));
// When
Optional<Organisation> result = organisationService.trouverParId(1L);
// Then
assertTrue(result.isPresent());
assertEquals("Lions Club Test", result.get().getNom());
verify(organisationRepository).findByIdOptional(1L);
}
@Test
void testTrouverParId_NonTrouve() {
// Given
when(organisationRepository.findByIdOptional(1L)).thenReturn(Optional.empty());
// When
Optional<Organisation> result = organisationService.trouverParId(1L);
// Then
assertFalse(result.isPresent());
verify(organisationRepository).findByIdOptional(1L);
}
@Test
void testTrouverParEmail_Success() {
// Given
when(organisationRepository.findByEmail("test@lionsclub.org")).thenReturn(Optional.of(organisationTest));
// When
Optional<Organisation> result = organisationService.trouverParEmail("test@lionsclub.org");
// Then
assertTrue(result.isPresent());
assertEquals("Lions Club Test", result.get().getNom());
verify(organisationRepository).findByEmail("test@lionsclub.org");
}
@Test
void testListerOrganisationsActives() {
// Given
List<Organisation> organisations = Arrays.asList(organisationTest);
when(organisationRepository.findAllActives()).thenReturn(organisations);
// When
List<Organisation> result = organisationService.listerOrganisationsActives();
// Then
assertNotNull(result);
assertEquals(1, result.size());
assertEquals("Lions Club Test", result.get(0).getNom());
verify(organisationRepository).findAllActives();
}
@Test
void testActiverOrganisation_Success() {
// Given
organisationTest.setStatut("SUSPENDUE");
organisationTest.setActif(false);
when(organisationRepository.findByIdOptional(1L)).thenReturn(Optional.of(organisationTest));
// When
Organisation result = organisationService.activerOrganisation(1L, "testUser");
// Then
assertNotNull(result);
assertEquals("ACTIVE", result.getStatut());
assertTrue(result.getActif());
assertEquals("testUser", result.getModifiePar());
assertNotNull(result.getDateModification());
}
@Test
void testSuspendreOrganisation_Success() {
// Given
when(organisationRepository.findByIdOptional(1L)).thenReturn(Optional.of(organisationTest));
// When
Organisation result = organisationService.suspendreOrganisation(1L, "testUser");
// Then
assertNotNull(result);
assertEquals("SUSPENDUE", result.getStatut());
assertFalse(result.getAccepteNouveauxMembres());
assertEquals("testUser", result.getModifiePar());
assertNotNull(result.getDateModification());
}
@Test
void testObtenirStatistiques() {
// Given
when(organisationRepository.count()).thenReturn(100L);
when(organisationRepository.countActives()).thenReturn(85L);
when(organisationRepository.countNouvellesOrganisations(any(LocalDate.class))).thenReturn(5L);
// When
Map<String, Object> result = organisationService.obtenirStatistiques();
// Then
assertNotNull(result);
assertEquals(100L, result.get("totalOrganisations"));
assertEquals(85L, result.get("organisationsActives"));
assertEquals(15L, result.get("organisationsInactives"));
assertEquals(5L, result.get("nouvellesOrganisations30Jours"));
assertEquals(85.0, result.get("tauxActivite"));
assertNotNull(result.get("timestamp"));
}
@Test
void testConvertToDTO() {
// When
var dto = organisationService.convertToDTO(organisationTest);
// Then
assertNotNull(dto);
assertEquals("Lions Club Test", dto.getNom());
assertEquals("LC Test", dto.getNomCourt());
assertEquals("test@lionsclub.org", dto.getEmail());
assertEquals("Organisation de test", dto.getDescription());
assertEquals("+225 01 02 03 04 05", dto.getTelephone());
assertEquals("Abidjan", dto.getVille());
assertEquals(25, dto.getNombreMembres());
assertTrue(dto.getActif());
}
@Test
void testConvertToDTO_Null() {
// When
var dto = organisationService.convertToDTO(null);
// Then
assertNull(dto);
}
@Test
void testConvertFromDTO() {
// Given
var dto = organisationService.convertToDTO(organisationTest);
// When
Organisation result = organisationService.convertFromDTO(dto);
// Then
assertNotNull(result);
assertEquals("Lions Club Test", result.getNom());
assertEquals("LC Test", result.getNomCourt());
assertEquals("test@lionsclub.org", result.getEmail());
assertEquals("Organisation de test", result.getDescription());
assertEquals("+225 01 02 03 04 05", result.getTelephone());
assertEquals("Abidjan", result.getVille());
}
@Test
void testConvertFromDTO_Null() {
// When
Organisation result = organisationService.convertFromDTO(null);
// Then
assertNull(result);
}
}