Spring之整合junit06
junit之程序的执行
1.应用程序的入口为main方法
2.junit单元测试中,没有main方法也可以执行
junit集成了一个main方法
该方法就会判断当前测试类中哪些方法有@Test注解
junit就让有@Test注解的方法执行
3.junit不会管我们是否采用spring框架
在执行测试的方法时,junit根本不知道我们是否使用了spring框架
所以也就不会为我们读取配置文件或者配置类创建spring容器
4.所以当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实行注入
spring整合junit配置
导入spring整合junit的jar包(坐标)
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
使用Junit提供的注解把原有的main方法替换,替换成spring提供的
@RunWith
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
public class springTest {
@Test
public void test01(){
}
}
搞直spring的运行期,spring和ioc创建时基于xml还是注解并说明位置
@ContextConfiguration
locations:指定xml文件的位置,加上classpath关键字表示在类路径下
classes:指定注解所在位置
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SpringConfiguration.class)
public class springTest {
@Test
public void test01(){
}
}