1.在Maven的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.编写测试类TestModule.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:applicationContext.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(); } } }
就可以使用单元测试进行代码的测试。