Spring的junit测试集成

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,点击绿色按钮
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值