1.pom.xml中加入
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency>
2.Java代码
package spring; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath*:/spring/servlet.xml","classpath*:/spring/common.xml"}) @Transactional @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false) public class TestModule { @Autowired ApplicationContext ctx; @Test public void testAdd() { try { UserManager userManager =ctx.getBean(UserManager.class); userManager.addUser(); } catch (Exception e) { e.printStackTrace(); } } }
3、总结
这里需要对defaultRollback = true 当然这里 只是在表中看不到数据, 但是如果你设置的主键是自动增长的话, 那么可以很明显得看出,虽然数据回滚了, 但是当你尝试不回滚新增数据到数据库的时候, 会发现ID不是连续的.所以并不是真正意义上的无污染 。这种方式也有他的好处,比单纯JUNIT要省去@before ,@after的方法.