Thursday, May 19, 2011

Quick and Dirty fixtures for tests

This is a quick and dirty approach that I use to quickly add fixtures for a entity test, say if I am testing an entity of the following type:

public class GtdContext {
    @Size(min = 1, max = 50)
    private String name;
In my test Spring context file, I have entries to instantiate beans of the type:
 <bean name="context1" class="org.bk.simplygtd.domain.GtdContext"  p:name="context1"/>
    <bean name="context2" class="org.bk.simplygtd.domain.GtdContext"  p:name="context2"/>
    <bean name="context3" class="org.bk.simplygtd.domain.GtdContext"  p:name="context3"/>
    <bean name="context4" class="org.bk.simplygtd.domain.GtdContext"  p:name="context4"/>
    <bean name="context5" class="org.bk.simplygtd.domain.GtdContext"  p:name="context5"/>

Now in my test class, I autowire in a Map in the following way:
 Map<String, GtdContext> gtdContextsMap;

Spring in this case autowires in all the GtdContexts instances into this Map, with the key as the bean name and the value being the instance. So now that the map is populated, a test embedded database can be populated with these fixtures:
<jdbc:embedded-database type="H2" id="dataSource"></jdbc:embedded-database>

  for (Map.Entry<String, GtdContext> entry:gtdContextsMap.entrySet()){

That is it! an embedded h2 database with some sample entries will be ready for tests

No comments:

Post a Comment