-
1. Re: Unit testing DB
nickarls Jun 2, 2009 9:04 AM (in response to nickarls)Still interested in the solution to this ;-)
Another issues that came up:
Does anyone know where to stick table creation scripts when running DB tests? I have some native queries that (not surprisingly) doesn't have their tables generated automagically...
-
2. Re: Unit testing DB
niox.nikospara.yahoo.com Jun 2, 2009 10:19 AM (in response to nickarls)Hi Nicklas,
I am not using JBoss Tools, I use seam-gen. But still this could be relevant.
I like to test the db and my entities standalone, i.e. without the SEAM testing framework, without running embedded JBoss etc. I have a class, DbTestUtils, with 3 static methods: createEmf() to create the EntityManagerFactory, importFromSqlFile() to run a SQL file and injectEm() to reflectively inject an entity manager into the fields of a bean or EJB implementation class annotated with @PersistenceContext.
The TestNG unit tests for the model are clean:
private static EntityManagerFactory emf; @BeforeSuite public void setup() throws Exception { emf = DbTestUtils.createEmf(); DbTestUtils.importFromSqlFile("/a/b/c/file1.sql", emf); DbTestUtils.importFromSqlFile("/a/b/c/file2.sql", emf); } @AfterSuite public void teardown() { emf.close(); } // ...test methods...
In test methods I can inject the EntityManager to test my business logic/DAOs:
// example of injection @Test public void testSomething() throws Exception { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); // THIS IS SFSB IMPL CLASS CompanyMgr cm = new CompanyMgrBean(); // INJECTION HERE DbTestUtils.injectEm(cm, em); ... }
In order to create the EntityManagerFactory, the createEmf() utilizes configuration information from three sources: (1) the persistence-test.xml, (2) some hardcoded values in DbTestUtils that override the persistence-test.xml, and (3) a separate persistence-overrides.properties file that overrides both. E.g. by specifying hibernate.hbm2ddl.auto=create-drop in DbTestUtils or persistence-test.xml I change the schema creation strategy. An example persistence-overrides.properties for your case could be:
# SPECIAL # This is the name of the EntityManagerFactory, to be used at creation # Should match the <persistence-unit name="..."> .nikos.EMF.name=xxxPU # STANDARD hibernate.connection.username=xxx hibernate.connection.password=yyy hibernate.connection.url=jdbc:hsqldb://localhost/your_test_db hibernate.hbm2ddl.auto=create-drop
The DbTestUtils itself is not too complicated. I'd be happy to provide it, together with detailed instructions, if you find this useful and relevant.