SpringBoot测试类

一、SpringBoot Test介绍

Spring Test与JUnit等其他测试框架结合起来,提供了便捷高效的测试手段。而Spring Boot Test 是在Spring Test之上的再次封装,增加了切片测试,增强了mock能力。

整体上,Spring Boot Test支持的测试种类,大致可以分为如下三类:

  • 单元测试:一般面向方法,编写一般业务代码时。涉及到的注解有@Test。
  • 切片测试:一般面向难于测试的边界功能,介于单元测试和功能测试之间。涉及到的注解有@RunWith @WebMvcTest等。
  • 功能测试:一般面向某个完整的业务功能,同时也可以使用切面测试中的mock能力,推荐使用。涉及到的注解有@RunWith @SpringBootTest等。

功能测试过程中的几个关键要素及支撑方式如下:

  • 测试运行环境:通过@RunWith 和 @SpringBootTest启动spring容器。
  • mock能力:Mockito提供了强大mock功能。
  • 断言能力:AssertJ、Hamcrest、JsonPath提供了强大的断言能力。

二、测试示例

2.1、单元测试

import org.junit.Test;
 
public class JavaTest {
    @Test
    public void test() {
        System.out.println(123);
    }
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 提供了多种测试注解和工具,可以方便地编测试。下面是一些常用的测试示例: 1. 单元测试 单元测试是用来测试单个或方法是否符合预期的,通常不需要启动 Spring 应用。 ```java import org.junit.Test; import static org.junit.Assert.assertEquals; public class MyTest { @Test public void test() { assertEquals(2, 1 + 1); } } ``` 2. 集成测试 集成测试是用来测试应用的各个组件是否能够协同工作,通常需要启动 Spring 应用。 ```java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class MyTest { @Autowired private MyService myService; @Test public void test() { myService.doSomething(); // 测试代码 } } ``` 3. Web测试 Web 测试是用来测试 Web 应用的,通常需要启动 Spring 应用,并使用 Spring Boot 提供的测试工具进行测试。 ```java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class MyTest { @Autowired private MockMvc mockMvc; @Test public void test() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/hello")) .andExpect(MockMvcResultMatchers.status().isOk()); } } ``` 在这个示例中,`@AutoConfigureMockMvc` 注解会自动配置一个 `MockMvc` 对象,用于模拟 HTTP 请求和响应。`mockMvc.perform()` 方法可以发送 HTTP 请求,`.andExpect()` 方法可以验证 HTTP 响应。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值