Spring 4.x 之 Test

    测试是开发工作中不可缺少的部分, 单元测试只针对当前开发的类和方法进行测试,可以简单的模拟依赖来实现,对环境没有依赖.但仅仅进行单元测试是不够的,他只能验证当前类或方法是否正常工作,而我们想知道系统的各部分组合在一起是否能正常工作,这就是集成测试存在的意义. Spring 通过 Spring TestContext Framework  对集成测试提供了顶级支持.它不依赖于特定的测试框架,既可以使用 Junit, 也可以用 TestNG.

    Spring 提供一个 SpringJUnit4ClassRunner 类,它提供了 Spring TestContext Framework 的功能. 通过 @ContextConfiguration 来配置 Application Context ,通过 @ActiveProfiles 确定活动的 Profiles.

示例:

package com.pangu.test;

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;
    }

}

配置:

package com.pangu.test;

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

@Configuration
public class TestConfig {
    
    @Bean
    @Profile("dev")
    public TestBean dev(){
        return new TestBean("开发环境..");
    }

    @Bean
    @Profile("prod")
    public TestBean prod(){
        return new TestBean("生产环境..");
    }
    
}

测试:

package com.pangu.test;

import static org.junit.Assert.assertEquals;

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)// 使用junit4进行测试
@ContextConfiguration(classes = TestConfig.class)//加载配置
@ActiveProfiles("dev")
public class SpringTest {
    @Autowired
    private TestBean testBean;

    @Test
    public void test() {
        String expected = "生产环境..";
        String content = testBean.getContent();
        assertEquals(expected, content);
    }
}

结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值