Quantcast
Channel: Zilverblog » Java
Viewing all articles
Browse latest Browse all 5

Spring testing on steriods

$
0
0

Recently I was involved in another Spring powered Java project and noticed a lot of test specific xml configuration floating around. Typically this is done because (for instance) datasources and such that are not available via JNDI outside a container. Problem that I have with the specific xml configuration is that it is maintenance intensive and well it is more xml… :-) Luckily you almost never have to create the specific XML files to be able to test your application context outside a container.

Let’s say we have a datasource configured in Spring like this:

[xml]

[/xml]

Instead of extracting this into a separate config file and combining those manually you can bind a datasource in your JUnit test using the SimpleNamingContextBuilder provided in the spring-test module. A datasource is easily created using the EmbeddedDatabaseBuilder.

A datasource is of course an easy example. What about the a Transaction Manager, or even worse the EntityManager (nice quote from a colleague: everything that uses the META-INF directory is suspicious). Even these are possible without having to duplicate the world. A complete test will look something like this.

[java]
public class SpringContextTest {
private EmbeddedDatabase dataSource;
private SimpleNamingContextBuilder contextBuilder;
private FileSystemXmlApplicationContext applicationContext;
@Before
public void setUp() throws NamingException {
dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).setName(“springtestdb”).build();
contextBuilder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
contextBuilder.bind(“java:jdbc/myDataSource”, dataSource);
contextBuilder.bind(“java:comp/UserTransaction”, new J2eeUserTransaction());
contextBuilder.bind(“persistence/MyPersistenceUnit”, createEntityManagerFactory());
}

private EntityManagerFactory createEntityManagerFactory() {
Map properties = new HashMap();
properties.put(“hibernate.hbm2ddl.auto”, “create-drop”);
properties.put(“javax.persistence.transactionType”, “RESOURCE_LOCAL”);
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(“MyPersistenceUnit”, properties);
return entityManagerFactory;
}

@After
public void tearDown() {
dataSource.shutdown();
contextBuilder.deactivate();
if(applicationContext != null) {
applicationContext.close();
}
}

@Test
public void springContextValid() throws Exception {
applicationContext = new FileSystemXmlApplicationContext(“application-context.xml”);
assertTrue(“success”, true);
}
}

[/java]

And the relevant xml part:

[xml]




[/xml]

By using the full power of the spring test module you can make testing your spring application context a lot easier.


Viewing all articles
Browse latest Browse all 5

Trending Articles