SpringBoot实战笔记:07_Spring 测试

Spring 测试

  • 测试是开发工作中不可或缺的部分。
  • 单元测试只针对当前开发的类和方法进行测试,可以简单通过模拟依赖来实现,对运行环境没有依赖。
  • 但是单元测试只能验证当前类或方法是否正常工作,而我们想要知道系统的各个部分组合在一起是否能正常工作,这就是集成测试存在的意义。
  • 集成测试为我们提供了一种无须部署或运行程序来完成验证系统各部分是否正常协同工作的能力。

Spring TestContext FrameWork

Spring 通过 TestContext FrameWork 对集成测试提供顶级支持。它不依赖于特定的测试框架。支持Junit也支持TestNG

简单示例

1,在pom.xml中添加Spring测试的依赖包
<!--07_新的依赖:使用Spring提供的集成测试-->
<dependency>
  <groupId>${spring-groupId}</groupId>
  <artifactId>spring-test</artifactId>
  <version>${spring-framework.version}</version>
</dependency>
2,创建目标Bean
package com.zyf;

import org.springframework.stereotype.Service;

/**
 * Created by zyf on 2018/3/5.
 */
@Service
public class TargetService {
    private String content;

    public TargetService(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
3,创建配置类
package com.zyf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * Created by zyf on 2018/3/5.
 */
@Configuration
public class TestConfig {

    @Bean
    @Profile("dev")
    public TargetService devTargetService(){
        //开发环境
        return new TargetService("for development profile");
    }

    @Bean
    @Profile("prod")
    public TargetService prodTargetService(){
        //生产环境
        return new TargetService("for production profile");
    }
}
4,在test/java/com.zyf下创建测试类
package com.zyf;

import org.junit.Assert;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by zyf on 2018/3/5.
 */
@RunWith(SpringJUnit4ClassRunner.class)
//在junit环境下提供Spring TestContext Framework的功能
@ContextConfiguration(classes = {TestConfig.class})
//加载配置ApplicationContext,classes参数用来加载配置类
@ActiveProfiles("prod")//声明当前正在活动的profile(可以理解为环境)
public class Test {

    @Autowired//注入
    private TargetService targetService;

    @org.junit.Test
    public void prodBeanShouldInject(){
        String expected = "for production profile";

        String actual = targetService.getContent();

        //判断二者是否相等
        Assert.assertEquals(expected,actual);

    }
}
5,测试结果

6,将ActionProfile由prod更改为dev后的测试结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值