Spring 测试

本文介绍如何使用Spring的SpringTestContextFramework进行集成测试,包括配置ApplicationContext、确定活动的profile,并通过示例展示了如何设置依赖注入的Bean及配置类,最后演示了具体的测试类实现。
  1. 集成测试一般需要来自不同层的不同对象的交互,如数据库、网络连接、Ioc容器等,集成测试提供了一种无需部署或运行程序来完成验证系统各个部分是否正常协同功能的能力。
  2. Spring通过Spring TestContext Framework对继承测试提供顶级支持,它不依赖于特定的测试框架,即可用Junit,也可以用TestNG。
  3. Spring提供了一个SpringJUnit4ClassRunner类,他提供了Spring TestContext Framework的功能。通过@ContextConfiguration来配置ApplicationContext,通过@ActiveProfiles确定活动的profile。

maven依赖

 <!--spring test 支持 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

依赖注入的Bean

/**
 * @author Kevin
 * @description
 * @date 2016/7/4
 */
public class TestBean {
    private String content;

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

配置类

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

/**
 * @author Kevin
 * @description
 * @date 2016/7/4
 */
@Configuration
public class TestConfig {
    @Bean
    @Profile("dev")
    public TestBean devTestBean(){
        return new TestBean("from devlopment profile");
    }

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

测试类

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;

/**
 * @author Kevin
 * @description
 * @date 2016/7/4
 */
// 在JUNIT环境下提供Spring TestContext Framework的功能
@RunWith(SpringJUnit4ClassRunner.class)
// 用来加载配置文件ApplicationContext,classes用来指定配置类
@ContextConfiguration(classes = {TestConfig.class})
// 用来声明profile范围
@ActiveProfiles("prod")
public class DemoBeanTest {
    @Autowired
    private TestBean testBean;

    @Test
    public void prodBeanInject() {
        String expect = "from production profile";
        String actual = testBean.getContent();
        Assert.assertEquals(expect, actual);
    }
}

 

转载于:https://my.oschina.net/kevinair/blog/705022

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值