SpringBoot Controller单元测试MockMvc

本文介绍了一个使用Spring Boot框架进行单元测试的例子,通过MockMvc工具类模拟HTTP请求,验证控制器层的功能实现。文章展示了如何设置测试环境、构造HTTP请求及断言响应状态。

直接看代码
package com.lemon.proudct.test;

import org.junit.Assert;
import org.junit.Before;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSON;
import com.lemon.product.ProductApplication;

/**
*
* @author jiangqk
* @data 2018年1月16日 下午5:23:41
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = ProductApplication.class)//Application启动类
public class MockTest {

@Autowired
private WebApplicationContext context;

private MockMvc mockMvc;

@Before
public void setUp() {
    //单个类,项目拦截器无效
//      mvc = MockMvcBuilders.standaloneSetup(new ProductController()).build();
        //项目拦截器有效
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

@Test
public void execute() throws  Exception {
    //调用接口,传入添加的用户参数
    RequestBuilder request = MockMvcRequestBuilders.post("/product/ec")
            .contentType(MediaType.APPLICATION_JSON_UTF8)  
            .content(JSON.toJSONString(null));

     MvcResult mvcResult = mockMvc.perform(request).andReturn() ;
     int status = mvcResult.getResponse().getStatus();  
     String content = mvcResult.getResponse().getContentAsString();
     Assert.assertTrue("正确", status == 200);  
     Assert.assertFalse("错误", status != 200);  
     System.out.println("返回结果:"+status);
     System.out.println(content);
}

}

Spring Boot应用程序中编写Controller层的单元测试,可以通过使用Spring Boot提供的测试工具和Mockito等框架来实现。以下是详细的实现步骤和方法: ### 使用 `MockMvc` 和 `@WebMvcTest` `@WebMvcTest` 是 Spring Boot 提供的一个注解,用于仅加载 Web 层(即 Controller 层)相关的 Bean,而不会加载其他组件(如 Service 或 Repository)。这种方式适合于隔离测试 Controller 的行为。 ```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.status; @WebMvcTest(controllers = DemoController.class) public class DemoControllerTest { @Autowired private MockMvc mockMvc; @Test public void shouldReturnDefaultMessage() throws Exception { mockMvc.perform(get("/demos")) .andExpect(status().isOk()); // 验证返回状态码为200 OK } } ``` ### 使用 `Mockito` 进行模拟测试 如果希望在不加载 Spring 上下文的情况下进行测试,可以使用 `Mockito` 框架来模拟 Controller 的依赖项(如 Service 层)。通过 `@Mock` 和 `@InjectMocks` 注解,可以创建和注入模拟对象。 ```java import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class MockDemoControllerTest { private MockMvc mockMvc; @Mock private IDemoService demoService; @InjectMocks private DemoController demoController; @BeforeEach public void setUp() { MockitoAnnotations.openMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(demoController).build(); } @Test public void should_get_demos() throws Exception { // 模拟 service 返回数据 when(demoService.findAll()).thenReturn(Collections.emptyList()); mockMvc.perform(get("/demos")) .andExpect(status().isOk()); // 验证返回状态码为200 OK } } ``` ### 使用 `@RunWith` 和 `@WebMvcTest` 的结合(JUnit 4) 如果使用的是 JUnit 4 而不是 JUnit 5,可以结合 `@RunWith` 和 `@WebMvcTest` 来测试 Controller: ```java import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @WebMvcTest(controllers = DemoController.class) public class DemoControllerJUnit4Test { // 这里可以注入 MockMvc 和其他依赖 } ``` ### 依赖配置 确保在 `pom.xml` 中引入了以下依赖,以便支持单元测试: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- 如果需要兼容 JUnit 4 --> <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <version>5.8.2</version> <scope>test</scope> </dependency> ``` ### 优势与适用场景 - **轻量级测试**:使用 `Mockito` 的方式可以避免加载整个 Spring 上下文,执行速度快,适合快速验证 Controller 的逻辑。 - **集成测试**:使用 `@WebMvcTest` 可以测试 ControllerSpring MVC 框架的集成,确保路由、参数绑定等行为正确。 通过上述方法,可以有效地为 Spring Boot 应用程序中的 Controller 编写单元测试,提高代码质量和可维护性。 ---
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值