IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Spring Java Discussion :

Configuration de spring pour faire des tests avec maven [Framework]


Sujet :

Spring Java

  1. #1
    Membre régulier
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    61
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2011
    Messages : 61
    Points : 70
    Points
    70
    Par défaut Configuration de spring pour faire des tests avec maven
    Bonjour.

    Je suis en train de réaliser un projet MultiModules utilisant Maven + JPA + Spring.

    Actuellement je n'ai que un sous module.

    Dans ce projet j'ai souhaité gérer mes dépendances avec SPRING directement dans ma classes de test.

    Avant de montrer l'erreur, voici l'organisation du projet (J'utilise le pattern daoJpa). Pour la partie src/main/java

    Entitée :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    103
    104
    105
    106
    107
    108
     
     
    import java.util.Date;
     
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
     
    @Entity
    @Table(name = "demandes_creation_compte")
    public class DemandeCreationCompte {
     
    	// -------------------------------------------------------------------------
    	// Attributs
    	// -------------------------------------------------------------------------
    	@Id
    	@GeneratedValue(strategy=GenerationType.AUTO)
    	@Column(name = "demande_creation_compte_id")
    	private long id;
     
    	@Column(name = "demande_creation_compte_email", nullable = false, length = 100, unique = true)
    	private String email;
     
    	@Column(name = "demande_creation_compte_pseudo", nullable = false, length = 40)
    	private String pseudo;
     
    	@Column(name = "demande_creation_compte_password", nullable = false, length = 40)
    	private String password;
     
    	@Column(name = "demande_creation_compte_code", nullable = false, length = 10)
    	private String code;
     
    	@Temporal(TemporalType.TIMESTAMP)
    	@Column(name = "demandes_creation_compte_date_demande_creation", nullable = false)
    	private Date dateDemandeCreation;
     
    	// -------------------------------------------------------------------------
    	// Constructeurs
    	// -------------------------------------------------------------------------
    	public DemandeCreationCompte(String email, String pseudo, String password,
    			String code, Date dateDemandeCreation) {
    		this.email = email;
    		this.pseudo = pseudo;
    		this.password = password;
    		this.code = code;
    		this.dateDemandeCreation = dateDemandeCreation;
    	}
     
    	public DemandeCreationCompte() {
    	}
     
    	// -------------------------------------------------------------------------
    	// Getter / Setter
    	// -------------------------------------------------------------------------
    	public long getId() {
    		return id;
    	}
     
    	public void setId(long id) {
    		this.id = id;
    	}
     
    	public String getEmail() {
    		return email;
    	}
     
    	public void setEmail(String email) {
    		this.email = email;
    	}
     
    	public String getPseudo() {
    		return pseudo;
    	}
     
    	public void setPseudo(String pseudo) {
    		this.pseudo = pseudo;
    	}
     
    	public String getPassword() {
    		return password;
    	}
     
    	public void setPassword(String password) {
    		this.password = password;
    	}
     
    	public String getCode() {
    		return code;
    	}
     
    	public void setCode(String code) {
    		this.code = code;
    	}
     
    	public Date getDateDemandeCreation() {
    		return dateDemandeCreation;
    	}
     
    	public void setDateDemandeCreation(Date dateDemandeCreation) {
    		this.dateDemandeCreation = dateDemandeCreation;
    	}
     
    }

    L'implémentation du daoJpa :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
     
     
    import java.lang.reflect.ParameterizedType;
    import java.util.List;
     
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
     
    import org.apache.log4j.Logger;
    import org.springframework.transaction.annotation.Transactional;
     
    import com.wsp.m2b.core.dao.exceptions.ExceptionDaoFind;
    import com.wsp.m2b.core.dao.exceptions.ExceptionDaoMerge;
    import com.wsp.m2b.core.dao.exceptions.ExceptionDaoPersist;
    import com.wsp.m2b.core.dao.exceptions.ExceptionDaoRefresh;
    import com.wsp.m2b.core.dao.exceptions.ExceptionDaoRemove;
    import com.wsp.m2b.core.dao.interfaces.DaoJpaInterface;
     
    public abstract class DaoJpaImpl<K, E> implements DaoJpaInterface<K, E> {
     
    	protected Logger log;
    	protected Class<E> entityClass;
    	@PersistenceContext(name="persistenceUnit")
    	protected EntityManager entityManager;
    	protected StringBuffer fromClause = null;
     
    	@SuppressWarnings("unchecked")
    	public DaoJpaImpl() {
    		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
    				.getGenericSuperclass();
    		this.entityClass = (Class<E>) genericSuperclass
    				.getActualTypeArguments()[1];
    		log = Logger.getLogger(this.entityClass);
    		fromClause = new StringBuffer("from ");
    		fromClause.append(entityClass.getSimpleName());
    	}
     
    	public void refresh(E entity) throws ExceptionDaoRefresh {
    		log.debug(entityClass.getSimpleName() + " persist start");
    		try {
    			entityManager.refresh(entity);
    			log.debug(entityClass.getSimpleName() + " persist end");
    		} catch (Exception e) {
    			log.error(e);
    			throw new ExceptionDaoRefresh(e);
    		}
    	}
     
    	public void persist(E entity) throws ExceptionDaoPersist {
    		log.debug(entityClass.getSimpleName() + " persist start");
    		try {
    			entityManager.persist(entity);
    			log.debug(entityClass.getSimpleName() + " persist end");
    		} catch (Exception e) {
    			log.error(e);
    			throw new ExceptionDaoPersist(e);
    		}
    	}
     
     
    	public void merge(E entity) throws ExceptionDaoMerge {
    		try {
    			log.debug(entityClass.getSimpleName() + " merge start");
    			entityManager.merge(entity);
    			log.debug(entityClass.getSimpleName() + " merge end");
    		} catch (Exception e) {
    			log.error(e);
    			throw new ExceptionDaoMerge(e);
    		}
    	}
     
     
    	public void remove(E entity) throws ExceptionDaoRemove {
    		try {
    			log.debug(entityClass.getSimpleName() + " remove start");
    			entityManager.remove(entity);
    			log.debug(entityClass.getSimpleName() + " remove end");
    		} catch (Exception e) {
    			log.error(e);
    			throw new ExceptionDaoRemove(e);
    		}
    	}
     
     
    	public E findById(K id) throws ExceptionDaoFind {
    		E response;
     
    		try {
    			log.debug(entityClass.getSimpleName() + " findById start");
    			response = entityManager.find(entityClass, id);
    			log.debug(entityClass.getSimpleName() + " findById end");
    			return response;
    		} catch (Exception e) {
    			log.error(e);
    			throw new ExceptionDaoFind(e);
    		}
    	}
     
    	@Transactional(readOnly = true)
    	public List<E> getAll() {
    		return entityManager.createQuery(fromClause.toString(), entityClass)
    				.getResultList();
    	}
     
     
    	public void setEntityManager(EntityManager entityManager) {
    		this.entityManager = entityManager;
    	}
     
    	public EntityManager getEntityManager() {
    		return entityManager;
    	}
    }
    Ma classe de dao
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
     
    import org.springframework.stereotype.Repository;
     
    import com.wsp.m2b.core.dao.interfaces.DaoDemandeCreationCompteInterface;
    import com.wsp.m2b.core.entites.DemandeCreationCompte;
     
    @Repository("daoDemandeCreationCompteImpl")
    public class DaoDemandeCreationCompteImpl extends
    		DaoJpaImpl<Long, DemandeCreationCompte> implements
    		DaoDemandeCreationCompteInterface {
     
    	public boolean isEmailExist(String email) {
     
    		String selectClause = "SELECT count(d) ";
    		String fromClause = "FROM DemandeCreationCompte AS d ";
    		String whereClause = "WHERE d.email=:email";
     
    		int total = entityManager
    				.createQuery(selectClause + fromClause + whereClause,
    						Long.class).setParameter("email", email)
    				.getSingleResult().intValue();
     
    		return !(total==0);
     
    	}
     
     
    }
    La partie src/test/java

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    import java.util.Date;
     
    import javax.annotation.Resource;
     
    import junit.framework.TestCase;
     
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.stereotype.Service;
     
    import com.wsp.m2b.core.commons.methodes.StaticMethodes;
    import com.wsp.m2b.core.commons.values.StaticValues;
    import com.wsp.m2b.core.dao.exceptions.ExceptionDaoPersist;
    import com.wsp.m2b.core.dao.interfaces.DaoDemandeCreationCompteInterface;
    import com.wsp.m2b.core.entites.DemandeCreationCompte;
     
    public class TestDemandeCreationCompte extends TestCase {
     
    	@Resource(name = "daoDemandeCreationCompteImpl")
    	DaoDemandeCreationCompteInterface daoDemandeCreationCompte ;
     
    	@Override    
    	protected void setUp() throws Exception {         
    		super.setUp();         
    		String[] springFiles = { "applicationContext.xml" };
    		ApplicationContext applicationContext = 
    			new ClassPathXmlApplicationContext(springFiles);
     
     
    	} 
     
    	@Test
    	public void testInsert(){
     
    		DemandeCreationCompte demandeCreationCompte = 
    			new DemandeCreationCompte(
    					"cryosore@gmail.com", 
    					"CrYoSoRe", 
    					"pass", 
    					StaticMethodes.generateCode(StaticValues.CODE_LENGTH), 				
    					new Date());
    		try {
     
    			daoDemandeCreationCompte.persist(demandeCreationCompte);
     
    		} catch (ExceptionDaoPersist e) {
    			e.printStackTrace();
    		}
     
    	}
     
     
    	public void setDaoDemandeCreationCompte(
    			DaoDemandeCreationCompteInterface daoDemandeCreationCompte) {
    		this.daoDemandeCreationCompte = daoDemandeCreationCompte;
    	}
    }
    Dans la partie src/test/resource
    (META-INF/) persistence.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    <persistence 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://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    	version="2.0">
     
    	<persistence-unit name="persistenceUnitTestHome"
    		transaction-type="RESOURCE_LOCAL">
     
    		<provider>org.hibernate.ejb.HibernatePersistence</provider>
     
    		<class>com.wsp.m2b.core.entites.DemandeCreationCompte</class>
     
    	<properties>
    		<property name="hibernate.hbm2ddl.auto" value="create-drop" />
    		<property name="hibernate.show_sql" value="true" />
    		<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
    		<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
    		<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test" />
    		<property name="hibernate.connection.username" value="root" />
    		<property name="hibernate.connection.password" value="" />
     
    		<property name="hibernate.c3p0.min_size" value="5" />
    		<property name="hibernate.c3p0.max_size" value="20" />
    		<property name="hibernate.c3p0.timeout" value="300" />
    		<property name="hibernate.c3p0.max_statements" value="50" />
    		<property name="hibernate.c3p0.idle_test_period" value="3000" />
    	</properties> 
     
    	</persistence-unit>
    </persistence>
    et le applicationContext de Spring :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    	xmlns:faces="http://www.springframework.org/schema/faces"
    	xmlns:int-security="http://www.springframework.org/schema/integration/security"
    	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:sec="http://www.springframework.org/schema/security"
    	xsi:schemaLocation="http://www.springframework.org/schema/integration/security http://www.springframework.org/schema/integration/security/spring-integration-security-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
    http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces-2.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
     
    	<context:component-scan base-package="com.wsp.m2b.core" />
    	<tx:annotation-driven />
     
    	<bean id="entityManagerFactory"
    		class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    		<property name="persistenceUnit" value="persistenceUnitTestHome" />
    	</bean>
     
    	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    		<property name="entityManagerFactory" ref="entityManagerFactory" />
    	</bean>
    </beans>
    Une fois que je lance les tests avec maven j'obtiens l'erreur suivante :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    -------------------------------------------------------------------------------
    Test set: com.wsp.m2b.core.dao.test.TestDemandeCreationCompte
    -------------------------------------------------------------------------------
    Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.571 sec <<< FAILURE!
    testInsert(com.wsp.m2b.core.dao.test.TestDemandeCreationCompte)  Time elapsed: 0.541 sec  <<< ERROR!
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'daoDemandeCreationCompteImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'persistenceUnit' of bean class [org.springframework.orm.jpa.LocalEntityManagerFactoryBean]: Bean property 'persistenceUnit' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    	at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:341)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
    	at com.wsp.m2b.core.dao.test.TestDemandeCreationCompte.setUp(TestDemandeCreationCompte.java:30)
    	at junit.framework.TestCase.runBare(TestCase.java:132)
    	at junit.framework.TestResult$1.protect(TestResult.java:110)
    	at junit.framework.TestResult.runProtected(TestResult.java:128)
    	at junit.framework.TestResult.run(TestResult.java:113)
    	at junit.framework.TestCase.run(TestCase.java:124)
    	at junit.framework.TestSuite.runTest(TestSuite.java:243)
    	at junit.framework.TestSuite.run(TestSuite.java:238)
    	at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
    	at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:35)
    	at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:146)
    	at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:97)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    	at java.lang.reflect.Method.invoke(Unknown Source)
    	at org.apache.maven.surefire.booter.ProviderFactory$ClassLoaderProxy.invoke(ProviderFactory.java:103)
    	at $Proxy0.invoke(Unknown Source)
    	at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:145)
    	at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcess(SurefireStarter.java:87)
    	at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:69)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'persistenceUnit' of bean class [org.springframework.orm.jpa.LocalEntityManagerFactoryBean]: Bean property 'persistenceUnit' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    	at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:529)
    	at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:495)
    	at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:656)
    	at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:629)
    	at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:147)
    	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    	at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:338)
    	... 33 more
    Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'persistenceUnit' of bean class [org.springframework.orm.jpa.LocalEntityManagerFactoryBean]: Bean property 'persistenceUnit' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    	at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1024)
    	at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:900)
    	at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
    	at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
    	... 47 more
    Je ne connais pas tres bien Spring mais je ne vois pas pourquoi il me sort cette erreur ....

    En remerciant à l'avance ceux qui prendraient le temps de se pencher sur mon cas

  2. #2
    Membre averti
    Homme Profil pro
    Inscrit en
    Avril 2011
    Messages
    214
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Avril 2011
    Messages : 214
    Points : 338
    Points
    338
    Par défaut
    Bonjour,

    Spring n'est pas content car
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'persistenceUnit' of bean class [org.springframework.orm.jpa.LocalEntityManagerFactoryBean]: Bean property 'persistenceUnit' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    c'est à dire il ne sait pas comment écrire la propriété 'persistenceUnit' du bean 'entityManagerFactory' comme tu lui a demandé ici:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    <bean id="entityManagerFactory"
    		class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    	<property name="persistenceUnit" value="persistenceUnitTestHome" />
    </bean>
    Or ce bean est de type LocalEntityManagerFactoryBean qui n'a en effet pas de méthode setPersistenceUnit() mais qui a une méthode setPersistenceUnitName()

    Donc il suffit de corriger applicationContext.xml avec le bon nom de propriété

  3. #3
    Membre régulier
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    61
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2011
    Messages : 61
    Points : 70
    Points
    70
    Par défaut
    Merci de votre réponse !

    Effectivement avec correction ca fonctionne mieux... pour cette partie


    En continuant mes tests il m'affiche:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    java.lang.NullPointerException
    	at com.wsp.m2b.core.dao.test.TestDemandeCreationCompte.testInsert(TestDemandeCreationCompte.java:51)
    Après divers tests il semble donc qu'il ne fasse pas d'injection de dépendance sur

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    @Resource(name = "daoDemandeCreationCompteImpl")
    	DaoDemandeCreationCompteInterface daoDemandeCreationCompte ;
    Dans la classe de test (ci-dessous pour eviter de naviguer dans la page)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    public class TestDemandeCreationCompte extends TestCase {
     
    	@Resource(name = "daoDemandeCreationCompteImpl")
    	DaoDemandeCreationCompteInterface daoDemandeCreationCompte ;
     
    	@Override    
    	protected void setUp() throws Exception {         
    		super.setUp();         
    		String[] springFiles = { "applicationContext.xml" };
    		ApplicationContext applicationContext = 
    			new ClassPathXmlApplicationContext(springFiles);
     
    		//daoDemandeCreationCompte = (DaoDemandeCreationCompteImpl) applicationContext.getBean("daoDemandeCreationCompteImpl");
     
    	} 
     
    	@Test
    	public void testInsert(){
     
    		System.out.println(daoDemandeCreationCompte);
     
    		DemandeCreationCompte demandeCreationCompte = 
    			new DemandeCreationCompte(
    					"cryosore@gmail.com", 
    					"CrYoSoRe", 
    					"pass", 
    					StaticMethodes.generateCode(StaticValues.CODE_LENGTH), 				
    					new Date());
    		try {
     
    			daoDemandeCreationCompte.persist(demandeCreationCompte);
     
    		} catch (ExceptionDaoPersist e) {
    			e.printStackTrace();
    		}
     
    	}
     
     
     
    	public DaoDemandeCreationCompteInterface getDaoDemandeCreationCompte() {
    		return daoDemandeCreationCompte;
    	}
     
    	public void setDaoDemandeCreationCompte(
    			DaoDemandeCreationCompteInterface daoDemandeCreationCompte) {
    		this.daoDemandeCreationCompte = daoDemandeCreationCompte;
    	}
    }
    Je me suis dis qu'il fallait surement récuperer le bean depuis le fichier de context (bien qu'étonnant avec le scan des package) alors j'ai rajouté :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    	DaoDemandeCreationCompteInterface daoDemandeCreationCompte ;
     
    	@Override    
    	protected void setUp() throws Exception {         
    		super.setUp();         
    		String[] springFiles = { "applicationContext.xml" };
    		ApplicationContext applicationContext = 
    			new ClassPathXmlApplicationContext(springFiles);
     
    		// Ajout
    		daoDemandeCreationCompte = (DaoDemandeCreationCompteImpl) applicationContext.getBean("daoDemandeCreationCompteImpl");
     
    	}
    Mais avec ceci j'ai le droit à :
    Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.552 sec <<< FAILURE!
    testInsert(com.wsp.m2b.core.dao.test.TestDemandeCreationCompte) Time elapsed: 1.512 sec <<< ERROR!
    java.lang.ClassCastException: $Proxy17 cannot be cast to com.wsp.m2b.core.dao.implementations.DaoDemandeCreationCompteImpl

    ...Faut-il que je déclare manuellement chacun des beans ou j'ai mal configuré quelque chose ?

  4. #4
    Membre averti
    Homme Profil pro
    Inscrit en
    Avril 2011
    Messages
    214
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Avril 2011
    Messages : 214
    Points : 338
    Points
    338
    Par défaut
    Citation Envoyé par wsp_ape Voir le message
    Après divers tests il semble donc qu'il ne fasse pas d'injection de dépendance sur


    Dans la classe de test (ci-dessous pour eviter de naviguer dans la page)
    En effet, Spring n'injecte pas tout n'importe où. Pour les classes de l'application cela fonctionne lorsqu'elles sont gérées par Spring, car annotées avec @Service ou autre.

    Pour les classes de test, l'approche est différente...
    Une réponse courte au problème pourrait être de rajouter:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    public class TestDemandeCreationCompte extends TestCase {
    Pour une réponse plus longue, il vaut mieux se référer à la doc de Spring sur les tests (notamment le §8.3.6 et suivants)

  5. #5
    Membre régulier
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    61
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2011
    Messages : 61
    Points : 70
    Points
    70
    Par défaut
    Merci des infos !

    Effectivement documentatation assez intéressante

    J'en ai profité pour modifier quelques infor ainsi que joindre spring-test dans mes dépendances ce qui me donne :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    package com.wsp.m2b.core.dao.test;
     
    import java.util.Date;
     
    import javax.annotation.Resource;
     
    import junit.framework.TestCase;
     
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.stereotype.Service;
    import org.springframework.test.context.ContextConfiguration;
     
    import com.wsp.m2b.core.commons.methodes.StaticMethodes;
    import com.wsp.m2b.core.commons.values.StaticValues;
    import com.wsp.m2b.core.dao.exceptions.ExceptionDaoPersist;
    import com.wsp.m2b.core.dao.implementations.DaoDemandeCreationCompteImpl;
    import com.wsp.m2b.core.dao.interfaces.DaoDemandeCreationCompteInterface;
    import com.wsp.m2b.core.entites.DemandeCreationCompte;
     
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"applicationContext.xml"})
    public class TestDemandeCreationCompte extends TestCase {
     
     
    	DaoDemandeCreationCompteInterface daoDemandeCreationCompte ;
     
    	@Override    
    	protected void setUp() throws Exception {         
    		super.setUp();         
    	} 
     
    	@Test
    	public void testInsert(){
     
    		System.out.println(daoDemandeCreationCompte);
     
    		DemandeCreationCompte demandeCreationCompte = 
    			new DemandeCreationCompte(
    					"cryosore@gmail.com", 
    					"CrYoSoRe", 
    					"pass", 
    					StaticMethodes.generateCode(StaticValues.CODE_LENGTH), 				
    					new Date());
    		try {
     
    			daoDemandeCreationCompte.persist(demandeCreationCompte);
     
    		} catch (ExceptionDaoPersist e) {
    			e.printStackTrace();
    		}
     
    	}
     
     
    	@Autowired
    	public void setDaoDemandeCreationCompte(
    			DaoDemandeCreationCompteInterface daoDemandeCreationCompte) {
    		this.daoDemandeCreationCompte = daoDemandeCreationCompte;
    	}
    }
    Cepedant il me sourligne en rouge la partie SpringJUnit4ClassRunner.class en me disant qu'il ne peut pas le résoudre comme un type.

    Si j'en crois la doc il se sert de ceci pour "parser/instancier" le fichier de configuration xml.
    Comment puis-je trouver cette classe ?

  6. #6
    Membre averti
    Homme Profil pro
    Inscrit en
    Avril 2011
    Messages
    214
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Avril 2011
    Messages : 214
    Points : 338
    Points
    338
    Par défaut
    Normalement c'est bien dans "spring-test". Qu'elle est la version utilisée ?

  7. #7
    Membre régulier
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    61
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2011
    Messages : 61
    Points : 70
    Points
    70
    Par défaut
    Je suis en 3.0.5.RELEASE pour Spring

  8. #8
    Membre régulier
    Homme Profil pro
    Inscrit en
    Mai 2011
    Messages
    61
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2011
    Messages : 61
    Points : 70
    Points
    70
    Par défaut
    Après un gros clean j'ai bien tout de bon. (votre remarque m'a mit la puce à l'oreille)

    Maintenant j'arrive à un

    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [com/wsp/m2b/core/dao/test/applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [com/wsp/m2b/core/dao/test/applicationContext.xml] cannot be opened because it does not exist

    Il semblerait qu'il ne me le cherche pas dans src/test/resources.
    Je vais continuer mes investigations

    Edit : Trouvé

    J'ai rajouté classpath:/ devant le nom du fichier spring dans l'annotation.

    Merci de votre aide

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [TestLink] Comment configurer Test_Link pour faire des tests automatisés ?
    Par bilred dans le forum Bibliothèques et frameworks
    Réponses: 8
    Dernier message: 06/02/2012, 14h41
  2. Attribut/Configuration pour répéter des tests avec VS2008
    Par hegros dans le forum Visual Studio
    Réponses: 8
    Dernier message: 08/09/2010, 17h38
  3. Réponses: 3
    Dernier message: 21/01/2009, 18h14
  4. Comment faire des test avec boost::test
    Par cdm1024 dans le forum Boost
    Réponses: 5
    Dernier message: 19/02/2008, 18h37
  5. [SQL] Récupération éventuelle d'une variable pour faire des tests
    Par mougeole dans le forum PHP & Base de données
    Réponses: 4
    Dernier message: 24/05/2006, 13h56

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo