Problème inserction des données avec JUnit
Bonjour,
Je suis en trin de réaliser une application avec spring mvc 3.
Je viens de terminer les couces dao, entites et métier (services). Maintenant, je suis en trin de faire des test unitaire pour m'assurer il n' y a pas des problème au niveau du métier avant que je passe à la couche web.
L'application génère bien les tables de la base de données mais il n'arrive pas à écrire dans la base de donnée et je ne retrouve pas l'erreur.
voici mon code:
ApplicationContext.xml:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/universityplus"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
<bean id="persistenceManagerUnit"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="datasource"></property>
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceManagerUnit"></property>
<property name="persistenceUnitName" value="UP_UNIVERSITE"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config></context:annotation-config>
<bean id="dao" class="com.gestion.universite.dao.UniversiteDaoImp"></bean>
<!-- pour administrateur. la réference fait à id=dao et name au
proprité dao du IAdminDaoMetierImp -->
<bean id="metierAdmin" class="com.gestion.universite.metier.IAdminDaoMetierImp">
<property name="dao" ref="dao"></property>
</bean>
</beans> |
persistance.xml:
Code:
1 2 3 4 5 6 7 8 9 10 11
| <?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_0.xsd ">
<persistence-unit name="UP_UNIVERSITE" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence> |
1. couche entite:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| package com.gestion.universite.entite;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
public class Etudiant implements Serializable{
@Id
@Size(min=5,max=15)
private String Mat_etud;
@NotEmpty
@Size(min=10,max=50)
private String Noms_etud;
@NotEmpty
@Size(min=5,max=15)
private String Prenom_etud;
@NotEmpty
@Size(min=10,max=50)
private String Adresse_etud;
@NotEmpty
private String Sexe_etud;
private Date datenaissance;
public Etudiant() {
super();
// TODO Auto-generated constructor stub
}
public Etudiant(String mat_etud, String noms_etud, String prenom_etud,
String adresse_etud, String sexe_etud, Date datenaissance) {
super();
Mat_etud = mat_etud;
Noms_etud = noms_etud;
Prenom_etud = prenom_etud;
Adresse_etud = adresse_etud;
Sexe_etud = sexe_etud;
this.datenaissance = datenaissance;
}
public Etudiant(String mat_etud) {
super();
Mat_etud = mat_etud;
}
public String getMat_etud() {
return Mat_etud;
}
public void setMat_etud(String mat_etud) {
Mat_etud = mat_etud;
}
public String getNoms_etud() {
return Noms_etud;
}
public void setNoms_etud(String noms_etud) {
Noms_etud = noms_etud;
}
public String getPrenom_etud() {
return Prenom_etud;
}
public void setPrenom_etud(String prenom_etud) {
Prenom_etud = prenom_etud;
}
public String getAdresse_etud() {
return Adresse_etud;
}
public void setAdresse_etud(String adresse_etud) {
Adresse_etud = adresse_etud;
}
public String getSexe_etud() {
return Sexe_etud;
}
public void setSexe_etud(String sexe_etud) {
Sexe_etud = sexe_etud;
}
public Date getDatenaissance() {
return datenaissance;
}
public void setDatenaissance(Date datenaissance) {
this.datenaissance = datenaissance;
}
} |
2.couche dao:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
package com.gestion.universite.dao;
import java.util.List;
import com.gestion.universite.entite.Etudiant;
public interface UniversiteDao {
//etudiant
public String creerEtudiant(Etudiant et);
public void saveEtudiant(Etudiant et);
public void modifierEtudiant(Etudiant et);
public void supprimerEtudiant(String mat_etud);
public List<Etudiant>listEtudiantParPromotion(String code_promo,String annee);
public List<Etudiant>listEtudiantParMotCle(String nom);
public Etudiant consulterEtudiant(String mat_etud);
} |
son interface:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package com.gestion.universite.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.gestion.universite.entite.Etudiant;
public class UniversiteDaoImp implements UniversiteDao {
@PersistenceContext
private EntityManager em;
@Override
public String creerEtudiant(Etudiant et) {
//System.out.println("recu:"+et.getNoms_etud());
em.persist(et);
return et.getMat_etud();
}
@Override
public void modifierEtudiant(Etudiant et) {
em.merge(et);
}
@Override
public void supprimerEtudiant(String mat_etud) {
Etudiant etudiant=consulterEtudiant(mat_etud);
em.remove(etudiant);
}
@Override
public List<Etudiant> listEtudiantParPromotion(String code_promo,
String annee) {
Query req=em.createQuery("select a from Etudiant a join Inscrit b where a.Mat_Etud = b.etudiant.Mat_Etud and b.promotion.code_promo = :value1");
req.setParameter("x",code_promo);
return req.getResultList();
}
@Override
public List<Etudiant> listEtudiantParMotCle(String nom) {
Query req=em.createQuery("select e from Etudiant e where e.Noms_etud like :x");
req.setParameter("x","%"+nom+"%");
return req.getResultList();
}
@Override
public Etudiant consulterEtudiant(String mat_etud) {
// TODO Auto-generated method stub
Etudiant et= em.find(Etudiant.class, mat_etud);
if(et==null) throw new RuntimeException("Etudiant "+mat_etud+" introuvable");
return et;
}
@Override
public void saveEtudiant(Etudiant et) {
em.persist(et);
}
} |
3. couche metier:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package com.gestion.universite.metier;
import java.util.List;
import com.gestion.universite.entite.Etudiant;
public interface IAdminDaoMetier {
//etudiant
public String creerEtudiant(Etudiant et);
public void saveEtudiant(Etudiant et);
public void modifierEtudiant(Etudiant et);
public void supprimerEtudiant(String mat_etud);
public List<Etudiant>listEtudiantParPromotion(String code_promo,String annee);
public List<Etudiant>listEtudiantParMotCle(String nom);
public Etudiant consulterEtudiant(String mat_etud);
} |
son interface
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| package com.gestion.universite.metier;
import java.util.List;
import com.gestion.universite.dao.UniversiteDao;
import com.gestion.universite.entite.Etudiant;
public class IAdminDaoMetierImp implements IAdminDaoMetier {
private UniversiteDao dao;
public void setDao(UniversiteDao dao) {
this.dao = dao;
}
@Override
public String creerEtudiant(Etudiant et) {
//System.out.println("avant...");
return dao.creerEtudiant(et);
}
@Override
public void modifierEtudiant(Etudiant et) {
// TODO Auto-generated method stub
dao.modifierEtudiant(et);
}
@Override
public void supprimerEtudiant(String mat_etud) {
// TODO Auto-generated method stub
dao.supprimerEtudiant(mat_etud);
}
@Override
public List<Etudiant> listEtudiantParPromotion(String code_promo,
String annee) {
// TODO Auto-generated method stub
return dao.listEtudiantParPromotion(code_promo, annee);
}
@Override
public List<Etudiant> listEtudiantParMotCle(String nom) {
// TODO Auto-generated method stub
return dao.listEtudiantParMotCle(nom);
}
@Override
public Etudiant consulterEtudiant(String mat_etud) {
// TODO Auto-generated method stub
return dao.consulterEtudiant(mat_etud);
}
@Override
public void saveEtudiant(Etudiant et) {
dao.saveEtudiant(et);
}
} |
Test unitaire avec JUnit:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
package com.gestion.universite;
import static org.junit.Assert.*;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.gestion.universite.entite.Etudiant;
import com.gestion.universite.metier.IAdminDaoMetier;
public class TestJPA {
@Test
public void test() {
try {
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext
(new String[]{"applicationContext.xml"});
//nous demandons d'appeler le bean metier que nous avons créer dans
//applicationContext. Ce bean était reservé pour IAdminMetierImp
IAdminDaoMetier metier=(IAdminDaoMetier)context.getBean("metierAdmin");
////List<Etudiant> et1=metier.listEtudiantParMotCle("wangi NGOY");
metier.saveEtudiant(new Etudiant("AE12345","WANGI NGOY","eric",
"lubudi 58", "M",new Date()));
assertTrue(true);
//assertTrue(et1.size() +2==et2.size());
} catch (Exception e) {
// TODO: handle exception
assertTrue(e.getMessage(),false);
}
}
} |
A l'exécution:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
INFO : org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1ed9554: startup date [Mon Aug 15 16:53:57 WAT 2016]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver
INFO : org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'UP_UNIVERSITE'
INFO : org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
INFO : org.hibernate.cfg.Environment - Hibernate 3.6.0.Final
INFO : org.hibernate.cfg.Environment - hibernate.properties not found
INFO : org.hibernate.cfg.Environment - Bytecode provider name : javassist
INFO : org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
INFO : org.hibernate.ejb.Version - Hibernate EntityManager 3.6.0.Final
INFO : org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [
name: UP_UNIVERSITE
...]
INFO : org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.gestion.universite.entite.Etudiant
INFO : org.hibernate.cfg.annotations.EntityBinder - Bind entity com.gestion.universite.entite.Etudiant on table Etudiant
INFO : org.hibernate.cfg.Configuration - Hibernate Validator not found: ignoring
INFO : org.hibernate.validator.util.Version - Hibernate Validator 4.1.0.Final
INFO : org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO : org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO : org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO : org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
INFO : org.hibernate.connection.ConnectionProviderFactory - Initializing connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
INFO : org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider - Using provided datasource
INFO : org.hibernate.cfg.SettingsFactory - Database ->
name : MySQL
version : 5.5.24-log
major : 5
minor : 5
INFO : org.hibernate.cfg.SettingsFactory - Driver ->
name : MySQL Connector Java
version : mysql-connector-java-5.1.36 ( Revision: 4fc1f969f740409a4e03750316df2c0e429f3dc8 )
major : 5
minor : 1
INFO : org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect
INFO : org.hibernate.transaction.TransactionFactoryFactory - Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory
INFO : org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
INFO : org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
INFO : org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
INFO : org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
INFO : org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
INFO : org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
INFO : org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
INFO : org.hibernate.cfg.SettingsFactory - Connection release mode: auto
INFO : org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
INFO : org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
INFO : org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
INFO : org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
INFO : org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
INFO : org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO : org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
INFO : org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
INFO : org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: enabled
INFO : org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
INFO : org.hibernate.cfg.SettingsFactory - Query cache: disabled
INFO : org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
INFO : org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
INFO : org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
INFO : org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
INFO : org.hibernate.cfg.SettingsFactory - Statistics: disabled
INFO : org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
INFO : org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
INFO : org.hibernate.cfg.SettingsFactory - Named query checking : enabled
INFO : org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): disabled
INFO : org.hibernate.impl.SessionFactoryImpl - building session factory
INFO : org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
INFO : org.hibernate.tool.hbm2ddl.SchemaUpdate - Running hbm2ddl schema update
INFO : org.hibernate.tool.hbm2ddl.SchemaUpdate - fetching database metadata
INFO : org.hibernate.tool.hbm2ddl.SchemaUpdate - updating schema
INFO : org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO : org.hibernate.tool.hbm2ddl.TableMetadata - table found: universityplus.etudiant
INFO : org.hibernate.tool.hbm2ddl.TableMetadata - columns: [adresse_etud, mat_etud, sexe_etud, prenom_etud, noms_etud, datenaissance]
INFO : org.hibernate.tool.hbm2ddl.TableMetadata - foreign keys: []
INFO : org.hibernate.tool.hbm2ddl.TableMetadata - indexes: [primary]
INFO : org.hibernate.tool.hbm2ddl.SchemaUpdate - schema update complete
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@137e670: defining beans [datasource,persistenceManagerUnit,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,dao,metierAdmin,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy |