Spring 4.x 之 Test

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29689487/article/details/82899367

    测试是开发工作中不可缺少的部分, 单元测试只针对当前开发的类和方法进行测试,可以简单的模拟依赖来实现,对环境没有依赖.但仅仅进行单元测试是不够的,他只能验证当前类或方法是否正常工作,而我们想知道系统的各部分组合在一起是否能正常工作,这就是集成测试存在的意义. 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);
    }
}

结果:

猜你喜欢

转载自blog.csdn.net/qq_29689487/article/details/82899367