Spring Boot多环境单元测试@ActiveProfiles例子

@ActiveProfiles是一个类注解,在Spring单元测试加载ApplicationContext时指定profiles。
@ActiveProfiles有以下参数:
profiles: 指定配置文件
resolver: 指定ActiveProfilesResolver,通过代码指定配置文件
value: profiles的别名
inheritProfiles: 配置文件是否继承父类,默认为true

@ActiveProfiles 在单元测试中使用的例子:

@ExtendWith(SpringExtension.class)
@ActiveProfiles("prod")
@ContextConfiguration
public class ActiveProfileTest {
------
} 

如果想通过@ActiveProfiles指定多个配置文件,把单元测试和对应环境的配置分开然后组合起来,可以指定一个数组:

@ExtendWith(SpringExtension.class)
@ActiveProfiles({ "prod", "junit" })
@ContextConfiguration
public class ActiveProfileTest {
------
} 

在spring boot中使用单元测试

我们使用@ActiveProfiles 和 @SpringBootTest。@SpringBootTest是一个类注解,在springboot应用中用来创建一个测试类:

ActiveProfileTest.java

package com.concretepage;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.ActiveProfiles;
import com.concretepage.services.Animal;

@ActiveProfiles({ "prod", "lion" })
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ActiveProfileTest {
	@Autowired
	private Animal animal;
	@Autowired
	private TestRestTemplate restTemplate;

	@Test
	public void serviceTest() {
		String message = animal.getMessage();
		assertTrue("Hello Lion!".equals(message));
	}

	@Test
	public void webAppTest() {
		String url = "http://localhost:8585/spring-boot-prod/";
		String body = this.restTemplate.getForObject(url, String.class);
		assertTrue("Hello Lion!".equals(body));
	}
} 
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiegwei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值