首页 > 编程语言 > 详细

基于Junit的Spring集成测试方法

时间:2019-07-21 09:38:48      阅读:74      评论:0      收藏:0      [点我收藏+]

 

单元测试主要是对开发的类和方法进行测试,但是只有单元测试是不够的,集成测试通过才能确保整个系统功能正确,比如数据库链接,接口调用等多个数据对象交互都需要集成测试。如果项目存在使用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",运行结果:

技术分享图片

 

基于Junit的Spring集成测试方法

原文:https://www.cnblogs.com/c04s31602/p/11219961.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!