Junit 单元测试的使用方法

前言

我这里通过创建 SpringBoot 项目来测试 Junit
这里只对简单配置的 Application Context 和在测试中注入Bean 做演示,以后会更新此博客,会对 Spring 测试做更多的讲述。

示例

1.准备

增加Spring 测试的依赖包到 pom.xml(我这里使用 SpringBoot 创建项目,已经默认引入了相关的依赖),若 pom.xml 中没有相关依赖,可参考如下 依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
</dependency>
2.业务代码

在src/main/java 下的源码:

package zhy;

public class TestBean {
    private String content;

    public TestBean(String content){
        super();
        this.content = content;
    }

    public String getContent(){
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
3.配置类

在src/main/java 下的源码:

package zhy;

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

@Configuration
public class TestConfig {

    @Bean
    @Profile("dev")
    public TestBean devTestBean(){
        return new TestBean("from development profile");
    }

    @Bean
    @Profile("prod")
    public TestBean prodTestBean(){
        return new TestBean("from production profile");
    }
}
4.测试

在src/test/java 下的源码:

package zhy;

import org.junit.Assert;
import org.junit.Test;
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;

@RunWith(SpringJUnit4ClassRunner.class)//1
@ContextConfiguration(classes = {TestConfig.class})//2
@ActiveProfiles("prod")//3
public class DemoBeanIntegrationTests {

    @Autowired//4
    private TestBean testBean;

    @Test//5
    public void proBeanShouldInject(){
        String expected = "from production profile";
        String actual = testBean.getContent();
        Assert.assertEquals(expected, actual);
    }
}

代码解释
- 1.SpringJUnit4ClassRunner 在JUnit环境下提供 Spring TestContext Framework 的功能。
- 2.@ContextConfiguration 用来加载配置 ApplicationContext, 其中 classes 属性用来加载配置类。
- 3.@ActiveProfiles 用来声明活动的 profile。
- 4.可使用普通的 @Autowired 注入Bean。
- 5.测试代码,通过 JUnit 的 Assert 来校验结果是否和预期一致。

5.测试结果

这里写图片描述

将@ActiveProfiles(“prod”)改为@ActiveProfiles(“dev”),演示测试不能通过的场景如下所示:
这里写图片描述

总结

集成测试为我们提供了一种无须部署或运行程序来完成验证系统各部分是否能正常协同工作的能力。后期我还会对Spring的 JUnit 单元测定做更多讲述。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值