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:

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

@Autowired
PlatformTransactionManager transactionManager;

private TestContextManager testContextManager;

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

@Before
public void setUpSpringContext() throws Exception {
testContextManager = new TestContextManager(getClass());
testContextManager.prepareTestInstance(this);
}

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

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

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

}

0 comments:

Post a Comment