Home > Java > JUnit parameterized test with Spring autowiring AND transactions

JUnit parameterized test with Spring autowiring AND transactions

by paul on September 8, 2011

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;
            }
        });

    }

Comments on this entry are closed.

Previous post:

Next post: