Bonjour à tous ,

Je tente de mettre en place des tests unitaires de DAO , en tentant d'automatiser certaines tâches comme la génération de la ddl "globale".

Pour ce faire, j'utilise une tâche ant couplée à Hibernate Tools pour générer cette ddl.

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
 
<?xml version="1.0" encoding="UTF-8"?>
 
<project>
 
	<target name="generate-ddl">
    	<echo message="Maven Classpath :	${maven.compile.classpath}"/>
    	<echo message="Basedir : ${basedir}" />
 
        <taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpath="${maven.compile.classpath}"/>
 
        <hibernatetool destdir="${basedir}/src/test/resources">
        	<annotationconfiguration configurationfile="${basedir}/src/test/resources/hibernate.cfg.xml"/>
            <hbm2ddl 	drop="false" 
            			create="true" 
            			export="false"
            			update="false"
                     	outputfilename="database-generated.ddl"
                     	delimiter=";" 
            			format="true"/>
        </hibernatetool>
    </target>
 
	<target name="generate-doc">
    	<echo message="Maven Classpath :	${maven.compile.classpath}"/>
    	<echo message="Basedir : ${basedir}" />
		<mkdir dir="${basedir}/target/site/entities"/>
 
        <taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpath="${maven.compile.classpath}"/>
 
        <hibernatetool destdir="${basedir}/target/site/entities">
        	<annotationconfiguration configurationfile="${basedir}/src/test/resources/hibernate.cfg.xml"/>
        	<hbm2doc/>
        </hibernatetool>
	</target>
 
 
</project>
Mon premier soucis est que la ddl générée ne contient pas les instructions de création des différents schema défini sur mes entités. Je dois donc écrire moi même les instructions de création de schéma ( ce qui n'est pas non plus une tâche fastidieuse ).

Ensuite j'exécute mon "simple" test unitaire en initialisant HSQLDB en mémoire avec ce script.

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
 
 
    create table taskfreak.frk_project (
        projectId bigint generated by default as identity (start with 1),
        description varchar(255),
        name varchar(255),
        primary key (projectId),
        unique (projectId)
    );
 
    create table website.USERS (
        id bigint generated by default as identity (start with 1),
        EMAIL varchar(255) not null,
        LOGIN varchar(255) not null,
        PASSWORD varchar(255) not null,
        primary key (id),
        unique (id)
    );
 
    create table wordpress.wp_posts (
        id bigint generated by default as identity (start with 1),
        post_category bigint,
        comment_count bigint,
        comment_status varchar(255),
        post_content longvarchar,
        post_content_filtered longvarchar,
        post_date timestamp,
        post_excerpt varchar(255),
        guid varchar(255),
        menu_order bigint,
        post_mime_type varchar(255),
        post_modified time,
        post_name varchar(255),
        post_parent bigint,
        post_password varchar(255),
        to_ping longvarchar,
        ping_status varchar(255),
        pinged longvarchar,
        post_status varchar(255),
        post_title varchar(255),
        post_type varchar(255),
        post_author bigint,
        primary key (id),
        unique (id)
    );
 
    create table wordpress.wp_users (
        id bigint generated by default as identity (start with 1),
        user_activation_key varchar(255) not null,
        display_name varchar(255) not null,
        user_email varchar(255) not null,
        user_login varchar(255) not null,
        user_nicename varchar(255) not null,
        user_pass varchar(255) not null,
        user_registered timestamp not null,
        user_status bigint not null,
        user_url varchar(255) not null,
        primary key (id),
        unique (id)
    );
 
    alter table wordpress.wp_posts 
        add constraint FK16E0A6ED34D5A56F 
        foreign key (post_author) 
        references wordpress.wp_users;


Cependant , lors de l'initialisation des tables , je reçois cette erreur :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
 
ERROR 16-03-2009 10:36:41 (AbstractDaoTest.java:92) org.dbunit.dataset.NoSuchTableException: website.USERS
La classe abstraite de mes test :

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
 
package be.javainside.website.persistence.dao;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Scanner;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.XmlDataSet;
import org.dbunit.ext.hsqldb.HsqldbDataTypeFactory;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "applicationContext-hibernate-dao.xml", "applicationContext-dao-test.xml" })
public abstract class AbstractDaoTest {
 
	@Autowired
	private DataSourceDatabaseTester dbTester;
 
	private static Log logger = LogFactory.getLog("AbstractTest");
 
	private IDataSet getDataSet() throws Exception {
		return new XmlDataSet(getClass().getResourceAsStream(getDataSetFile()));
	}
 
	protected abstract String getDataSetFile();
 
	private void initDatabase() throws Exception {
 
		IDatabaseConnection dbConnection = dbTester.getConnection();
		Connection connection = dbConnection.getConnection();
 
		Statement statement = null;
		try {
			statement = connection.createStatement();
			statement.execute("CREATE SCHEMA taskfreak AUTHORIZATION DBA");
			statement.execute("CREATE SCHEMA website AUTHORIZATION DBA");
			statement.execute("CREATE SCHEMA wordpress AUTHORIZATION DBA");
			String sql = readSqlFile("/database-generated.ddl");
			statement.execute(sql);
 
		} finally {
			if (statement != null) {
				statement.close();
			}
		}
	}
 
	private void initDataSet() throws Exception {
		IDatabaseConnection dbConnection = dbTester.getConnection();
		dbConnection.getConfig().setFeature(DatabaseConfig.FEATURE_DATATYPE_WARNING, true);
		dbConnection.getConfig().setFeature(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);
		dbConnection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());
		DatabaseOperation.CLEAN_INSERT.execute(dbConnection, getDataSet());
	}
 
	private String readSqlFile(String fileName) throws FileNotFoundException {
		StringBuilder builder = new StringBuilder();
		Scanner scanner = new Scanner(new File(getClass().getResource(fileName).getFile()));
 
		while (scanner.hasNextLine()) {
			builder.append(scanner.nextLine());
		}
 
		scanner.close();
 
		return builder.toString();
	}
 
	@Before
	public void setUp() throws Exception {
 
		try {
			initDatabase();
			initDataSet();
		} catch (Exception e) {
			logger.error(e);
			throw e;
		}
	}
 
	@After
	public void tearDown() throws Exception {
		DatabaseOperation.DELETE_ALL.execute(dbTester.getConnection(), getDataSet());
 
	}
}
En vous remerciant d'avance.