1.原始Junit测试Spring的问题
每个测试方法都有以下两行代码
这两行代码是获取容器
2.上速问题解决
让SpringJunit负责创建Spring容器。但是需要将配置文件的名称告诉它
6.1Spring集成Junit步骤
1)导入spring集成Junit的坐标
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.5.RELEASE</version> </dependency>
2)使用@Runwith注解替换原来的运行器
3)使用@ContextConfiguration指定配置文件或配置类
4)使用@Autowired注入需要测试的对象
5)创建测试方法并创建
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.sql.DataSource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") //@ContextConfiguration(classes = {SpringConfig.class}) public class SpringJunitTest { @Autowired private UserService userService; @Autowired private DataSource dataSource; @Test public void test1() throws Exception { userService.save(); // System.out.println(dataSource.getConnection()); } }