Friday, 9 September 2011

JUnit parameterized test with Spring autowiring AND transactions

I've been writing JUnit Parameterized tests (a nice intro here - also see Theories) to do some data driven API testing. Now, when introducing Spring into the mix there are a couple of extra things to do. I came unstuck though because I was trying to do Transactional tests - since I'm now using @RunWith(Parameterized.class) and setting up my Spring TestContextManager manually the @Transaction annotations caused an exception:
java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given

I couldn't find any built in solution, so I've gone with manual transaction management in my test, using doInTransaction:

@ContextConfiguration(locations = "classpath*:/testContext.xml")
public class MyTest {

PlatformTransactionManager transactionManager;

private TestContextManager testContextManager;

public MyTest (... parameters for test) {
// store parameters in instance variables

public void setUpSpringContext() throws Exception {
testContextManager = new TestContextManager(getClass());

public static Collection generateData() throws Exception {
ArrayList list = new ArrayList();
// add data for each test here
return list;

public void validDataShouldLoadFully() throws Exception {
new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
try {
... do cool stuff here

} catch (Exception e) {
throw new RuntimeException(e);
return null;



Post a Comment