基于Junit的Spring集成测试方法

 单元测试主要是对开发的类和方法进行测试,但是只有单元测试是不够的,集成测试通过才能确保整个系统功能正确,比如数据库链接,接口调用等多个数据对象交互都需要集成测试。如果项目存在使用Spring框架,可通过Spring TestContext Framework在开发环境进行单元测试,且无须部署项目。Spring TestContext Framework不依赖具体的实现,既可使用Junit,也可使用TestNG等。

本文通过Spring集成JUnit的实例来演示基于Spring的项目的集成测试方法。

首先在SpringBoot项目中加入Maven依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

spring-boot-starter-test已经将JUnit依赖进来,建一个测试类:

public class TestService {

    private String profile;

    public TestService(String profile) {
        this.profile = profile;
    }

    public String getProfile() {
        return profile;
    }

}

配置类:

@Configuration
@ComponentScan("com.acwei.boot.test")
public class TestConfiguration {

    @Bean
    @Profile("dev")
    public TestService devService() {
        return new TestService("dev");
    }

    @Bean
    @Profile("prd")
    public TestService prdService() {
        return new TestService("prd");
    }

}

这里用到了Profile,主要是演示测试时对Profile的支持。JUnit测试类:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestConfiguration.class)
@ActiveProfiles("dev")
public class DemoTest {

    @Autowired
    private TestService testService;

    @Test
    public void test() {
        Assert.assertEquals("dev", testService.getProfile());
    }

}

这里有三个注解:

@RunWith:是JUnit的一个注解,加了这个注解的类将会被JUnit调用运行测试,其values是一个实现了Runner的类。这里的SpringRunner其实是org.springframework.test.context.junit4.SpringJUnit4ClassRunner的别名,而SpringJUnit4ClassRunner是对Junit Runner接口的扩展,加入了对Spring环境的支持。

@ContextConfiguration:加载Spring的配置。

@ActiveProfiles:激活Spring Profile。

运行结果:

如果将@ActiveProfiles注解值改为"prd",运行结果:

可以看到,除了@RunWith所有的代码都和Junit没有关系,不用再使用Junit的@Before、@After等注解,不用手动加载SpringApplicationContext对象,注入Spring Bean只需要加上@Autowired注解就可以了,其实其他Spring特性也可以直接使用而不必通过SpringApplicationContext对象。这主要归功于Junit提供的扩展接口Runner,以及Spring的实现类SpringJUnit4ClassRunner对Spring TestContext Framework框架的支持。

posted on 2019-07-21 00:56  c04s31602  阅读(176)  评论(0编辑  收藏  举报

导航