spring boot @test测试指定active

开发环境和测试环境一些配置还是不一样,用服务器上的jenkins跑测试,需要制定spring.profiles.active=pro

加上一个注解就好了

@ActiveProfiles("pro")
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

}

 

### Spring Boot 测试依赖配置与使用方法 Spring Boot 提供了一个强大的测试框架,支持单元测试和集成测试。为了实现这些功能,需要在项目中引入 `spring-boot-starter-test` 依赖项[^3]。该依赖项包含了常用的测试库,例如 JUnit、Mockito 和 AssertJ 等。 以下是将 `spring-boot-starter-test` 添加到 Maven 项目的示例: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> ``` 对于 Gradle 项目,可以使用以下配置: ```gradle dependencies { testImplementation('org.springframework.boot:spring-boot-starter-test') } ``` 引入此依赖后,可以编写基于 Spring Boot测试类。下面是一个简单的单元测试示例,展示如何测试一个 REST 控制器: ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest public class ExampleControllerTest { @Autowired private MockMvc mockMvc; @Test public void testExampleEndpoint() throws Exception { mockMvc.perform(get("/example")) .andExpect(status().isOk()) .andExpect(content().string("Hello, World!")); } } ``` 上述代码展示了如何使用 `@WebMvcTest` 注解来测试控制器的端点,并通过 `MockMvc` 执行 HTTP 请求验证响应状态和内容[^4]。 此外,Spring Boot 提供了 `@SpringBootTest` 注解,用于加载完整的应用程序上下文并执行更复杂的集成测试。例如: ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; @SpringBootTest public class IntegrationTest { @Autowired private MockMvc mockMvc; @Test public void testIntegration() throws Exception { // 测试逻辑 } } ``` 在某些情况下,可能需要为测试环境设置特定的属性或配置。可以通过创建 `application-test.properties` 文件并在测试指定 `spring.profiles.active=test` 来实现这一点[^5]。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值