如何在AbstractTransactionalJUnit4SpringContextTests事务中执行junit规则?

时间:2013-01-18 08:44:26

标签: spring testing junit

我想在测试方法事务中做一些数据库操作。我想为此使用junit TestRules。但规则是在交易之外执行的。有没有办法让我的规则在交易中执行?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:/META-INF/spring/applicationContext.xml"})
public class ProductServiceTest extends AbstractTransactionalJUnit4SpringContextTests {

public @Rule @Autowired MySimpleSpringRule mySimpleSpringRule;

@Before
public void before() {
    logger.debug("before");
}

@After
public void after() {
    logger.debug("after");
}

@Test
public void testFindProducts() {
...

@Component
public class MySimpleSpringRule implements TestRule {

private class Banaani extends ExternalResource {
    @Override
    protected void before() throws Throwable {
        logger.debug("before");
    };

    @Override
    protected void after() {
        logger.debug("after");
    };
}

private final Banaani banaani = new Banaani();

@Override
public Statement apply(Statement st, Description desc) {
    return banaani.apply(st, desc);
}

结果

2013-01-18 10:33:24,845 DEBUG [main]: MySimpleSpringRule         - before
2013-01-18 10:33:24,869 INFO  [main]: ionalTestExecutionListener - Began transaction (1): transaction manager [org.springframework.orm.jpa.JpaTransactionManager@a713a5]; rollback [true]
2013-01-18 10:33:24,869 DEBUG [main]: ProductServiceTest         - before
2013-01-18 10:33:24,869 DEBUG [main]: ProductServiceTest         - running test...
2013-01-18 10:33:24,984 DEBUG [main]: ProductServiceTest         - after
2013-01-18 10:33:24,986 INFO  [main]: ionalTestExecutionListener - Rolled back transaction after test execution for test context [[TestContext@67946a testClass = ProductServiceTest, testInstance = fi.liikennevirasto.service.ProductServiceTest@40f0b2, testMethod = testFindRootProducts@ProductServiceTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@17a6b96 testClass = ProductServiceTest, locations = '{classpath:/META-INF/spring/test-bean-configuration.xml, classpath:/META-INF/spring/applicationContext.xml, classpath:/META-INF/spring/infrastructure.xml}', classes = '{}', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]]
2013-01-18 10:33:24,987 DEBUG [main]: MySimpleSpringRule         - after

直接在测试类中的@Before和@After方法在事务中执行,但MySimpleSpringRule中的方法在事务外执行。

1 个答案:

答案 0 :(得分:0)

这可能无法使用@Rules ....?

如果没有,可以使用http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/test/context/TestExecutionListener.html

完成同样的事情