3.7 Spring高级话题: 测试

本文深入探讨了Spring测试框架的使用,包括如何配置依赖项、设置测试环境,以及通过示例展示如何在不同的环境下加载特定的配置类。文章还介绍了如何使用@RunWith、@ContextConfiguration和@ActiveProfiles注解来运行测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3.7 Spring高级话题: 测试

在这里插入图片描述

3.7 测试
1.测试的依赖

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.18.RELEASE</version>
    <scope>test</scope>
</dependency>

2.测试的配置

@RunWith(SpringJUnit4ClassRunner.class) //在Junit环境下提供Spring TestContext FrameWork
@ContextConfiguration(classes = TestConfig.class) //用来加载ApplicationContext配置,class属性是用来加载配置类
@ActiveProfiles(value = "pro")//用来声明活动的profile

举例:
1.Java配置

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

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Configuration
@ComponentScan("com.sgx.inspect.bug.test")
public class TestConfig {

    @Bean
    @Profile("dev")
    public List getDevBean() {
        System.out.println("初始化DevBean");
        List list = new ArrayList();
        list.add("dev");
        return list;
    }

    @Bean
    @Profile("pro")
    public List getProBean() {
        System.out.println("初始化ProBean");
        List list = new LinkedList();
        list.add("pro");
        return list;
    }
}

2.测试

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;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class) //在Junit环境下提供Spring TestContext FrameWork
@ContextConfiguration(classes = TestConfig.class) //用来加载ApplicationContext配置,class属性是用来加载配置类
@ActiveProfiles(value = "pro")//用来声明活动的偏好
public class TestMain {


    @Autowired
    private List list;

    @Test
    public void testLiat() {
        System.out.println("测试:" + list.get(0));
    }
}

3.输出

初始化ProBean
测试:pro
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值