如何使Spring @Transactional在junit测试中工作

时间:2015-10-01 18:09:27

标签: java spring junit spring-transactions spring-java-config

我尝试使用Spring @Transactional注释进行测试。

@ContextConfiguration(classes = SomeTest.SomeTestSpringConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SomeTest {

    @Autowired
    MyBean some;

    @Autowired
    PlatformTransactionManager transactionManager;

    @Test
    public void testSpring() throws Exception {
        some.method();
        assertTrue(some.isTransactionalWorks);
    }

    @EnableAspectJAutoProxy(proxyTargetClass = true)
    @EnableLoadTimeWeaving
    @EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
    @TransactionConfiguration
    static class SomeTestSpringConfig {

        @Bean
        PlatformTransactionManager transactionManager() {
            return new MyTransactionManager(dataSource());
        }

        @Bean
        MyBean some() {
            return new MyBean();
        }

        @Bean
        DataSource dataSource() {
            return new SimpleDriverDataSource(Driver.load(), "jdbc:h2:mem:unit-test");
        }
    }
}

class MyBean {

    @Autowired
    DataSource dataSource;

    public boolean isTransactionalWorks;

    @Transactional
    private void someInTransaction() {
        try {
            dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println("I should be in transaction");
    }

    public void method() {
        someInTransaction();
    }
}


class MyTransactionManager implements PlatformTransactionManager, InitializingBean {
    private final DataSourceTransactionManager base = new DataSourceTransactionManager();

    @Autowired
    MyBean some;

    public MyTransactionManager(DataSource datasource) {
        base.setDataSource(datasource);
    }

    @Override
    public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
        some.isTransactionalWorks = true;
        return base.getTransaction(definition);
    }

    @Override
    public void commit(TransactionStatus status) throws TransactionException {
        base.commit(status);
    }

    @Override
    public void rollback(TransactionStatus status) throws TransactionException {
        base.rollback(status);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        base.afterPropertiesSet();
    }
}

此外,我还为此测试的VM选项添加了-javaagent:D:/libs/spring-instrument-4.1.7.RELEASE.jar。 但它总是失败。我错过了什么?

1 个答案:

答案 0 :(得分:0)

请检查此链接,我认为这是您面临的类似问题。

How to configure AspectJ with Load Time Weaving without Interface

在这个链接中,他要求在vm参数中提供aspectjweaver.jar和spring-instrument.jar。

很高兴知道它有效。 :)