Create a gist now

Instantly share code, notes, and snippets.

Embed
PrepareAspectJTestExecutionListener resets the AnnotationTransactionAspect to point to the correct bean factory and platform transaction manager before execution
package com.github.steveash.gist;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.aspectj.AnnotationTransactionAspect;
/**
* Test Execution Listener that resets the references to the Annotation Transaction Aspect's
* bean factory and transaction manager instance if it has one. Otherwise it just clears it
* @author Steve Ash
*/
public class PrepareAspectJTestExecutionListener extends AbstractTestExecutionListener {
private final String trxManagerBeanName;
public PrepareAspectJTestExecutionListener(String trxManagerBeanName) {
this.trxManagerBeanName = trxManagerBeanName;
}
public PrepareAspectJTestExecutionListener() {
this("transactionManager");
}
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
super.beforeTestClass(testContext);
AnnotationTransactionAspect aspect = AnnotationTransactionAspect.aspectOf();
ApplicationContext ctx = testContext.getApplicationContext();
aspect.setBeanFactory(ctx);
if (ctx.containsBean(this.trxManagerBeanName)) {
aspect.setTransactionManagerBeanName(this.trxManagerBeanName);
PlatformTransactionManager trxMgr = ctx.getBean(trxManagerBeanName, PlatformTransactionManager.class);
aspect.setTransactionManager(trxMgr);
} else {
aspect.setTransactionManager(null);
aspect.setTransactionManagerBeanName(null);
}
}
}
package com.github.steveash.gist;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import com.github.steveash.gist.TestApp;
import com.github.steveash.gist.PrepareAspectJTestExecutionListener;
@ContextConfiguration(classes = TestApp.class)
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
PrepareAspectJTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class
})
public class AbstractTestFixture {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment