1.原始Junit测试Spring的问题
在测试类中,每个测试方法都有以下两行代码。每个测试都要重新启动Spring容器,启动容器的开销大,测试效率低下。
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常,所以不能轻易删掉
2.上述问题解决思路
(1)让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它
(2)将需要进行测试Bean直接在测试类中进行注入
3.Spring集成Junit步骤
(1)导入spring集成Junit坐标(在pom.xml中导入)
(2)使用@Runwith注解替换原来的运行期
(3)使用@ContextConfiguration指定配置文件或配置类
(4)使用@Autowired注入需要测试的对象
(5)创建测试方法进行测试
@RunWith作用
@RunWith 就是一个运行器
@RunWith(JUnit4.class) 就是指用JUnit4来运行
@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境
@RunWith(Suite.class) 的话就是一套测试集合,
@ContextConfiguration Spring整合JUnit4测试时,使用注解引入多个配置文件
这种写法是为了让测试在Spring容器环境下执行。 Spring的容器环境是啥呢? 比如常见的 Service Dao Action , 这些个东西,都在Spring容器里,junit需要将他们拿到,并且使用来测试。
package com.company.test; import com.company.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.sql.SQLException; import javax.sql.DataSource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class SpringJunitTest { // 测谁就将谁注入,加上@AutowiredSpring扫到这个注解之后, // 会尝试从Spring容器找到UserService类型的Bean,找到之后,直接给你注到这个地方 @Autowired private UserService userService; @Autowired private DataSource dataSource; @Test public void test1() throws SQLException { userService.save(); System.out.println(dataSource.getConnection()); } }
运行结果:
上面用的是加载配置文件xml的方式
下面使用全注解的方式
package com.company.test; import com.company.config.SpringConfiguration; import com.company.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.sql.SQLException; import javax.sql.DataSource; @RunWith(SpringJUnit4ClassRunner.class) // @ContextConfiguration("classpath:applicationContext.xml") @ContextConfiguration(classes = {SpringConfiguration.class}) public class SpringJunitTest { // 测谁就将谁注入,加上@AutowiredSpring扫到这个注解之后, // 会尝试从Spring容器找到UserService类型的Bean,找到之后,直接给你注到这个地方 @Autowired private UserService userService; @Autowired private DataSource dataSource; @Test public void test1() throws SQLException { userService.save(); System.out.println(dataSource.getConnection()); } }
SpringConfiguration
package com.company.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; // 标志该类是Spring的核心配置类(不要配置文件,不是意味着不要配置,原来的配置只是用类的方式代替文件,用注解的方式代替标签) @Configuration // <context:component-scan base-package="com.company"/> @ComponentScan("com.company") // <import resource=""/> @Import({DataSourceConfiguration.class}) public class SpringConfiguration { }