Spring提供spring-test-4.3.13.RELEASE 可以整合junit。
优势:可以简化测试代码
(不需要手动创建上下文)
pom.xml(spring4)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
使用spring和junit集成
第一步:
通过@RunWith注解,使用junit整合spring。通过@ContextConfiguration注解,指定spring容器的位置
SpringTest.java
import cn.itcast.spring.service.HelloService;
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;
//目标:测试一下spring的bean的某些功能
@RunWith(SpringJUnit4ClassRunner.class)//junit整合spring的测试//立马开启了spring的注解
@ContextConfiguration(locations="classpath:applicationContext.xml")//加载核心配置文件,自动构建spring容器
public class SpringTest {
//使用注解注入要测试的bean
@Autowired
private HelloService helloService;
@Test
public void testSayHello(){
helloService.sayHello();
}
}
上述代码表示:在测试类运行前的初始化的时候,会自动创建ApplicationContext对象
第二步:
通过@Autowired注解,注入需要测试的对象
在这里注意2点:
(1)将测试对象注入到测试用例中
(2)测试用例不需要配置<context:annotion-config/>,因为使用测试类运行的时候,会自动启动注解的支持。
//使用注解注入要测试的bean
@Autowired
private HelloService helloService;
第三步:
调用测试方法完成测试
@Test
public void testSayHello(){
helloService.sayHello();
}
不用启动tomcat,点击绿色按钮