Spring 测试

  1. 集成测试通常须要来自不一样层的不一样对象的交互,如数据库、网络链接、Ioc容器等,集成测试提供了一种无需部署或运行程序来完成验证系统各个部分是否正常协同功能的能力。
  2. Spring经过Spring TestContext Framework对继承测试提供顶级支持,它不依赖于特定的测试框架,便可用Junit,也能够用TestNG。
  3. Spring提供了一个SpringJUnit4ClassRunner类,他提供了Spring TestContext Framework的功能。经过@ContextConfiguration来配置ApplicationContext,经过@ActiveProfiles肯定活动的profile。

maven依赖java

<!--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>

依赖注入的Beanspring

/**
 * @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);
    }
}
相关文章
相关标签/搜索