Springboot项目:使用MockMvc测试get和post接口(含单个和多个请求参数场景)

一、引入MockMvc依赖

使用MockMvc,必须要引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

二、具体演示

1、GET请求(单个参数)

测试类代码

@ExtendWith(MockitoExtension.class)
class AppControllerTest {

    private MockMvc mockMvc;

    @Mock
    private IDB2PatrolResultService idb2PatrolResultService;
    @InjectMocks
    private DB2PatrolResultController db2PatrolResultController;

    @BeforeEach
    void setUp() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(db2PatrolResultController).build();
    }

    @Test
    void testGet() throws Exception {
        this.mockMvc.perform(MockMvcRequestBuilders.get("/dbm/patrolResult/trigger/{itemCode}","121"))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();
    }
}

controller类代码

	@GetMapping("/trigger/{itemCode}")
    public R<Void> execSchedule(@PathVariable("itemCode") String itemCode) {
        return patrolResultService.execSchedule(itemCode);
    }

2、GET请求(多个参数)

测试类代码:

@ExtendWith(MockitoExtension.class)
class AppControllerTest {

    private MockMvc mockMvc;

    @Mock
    private IDB2PatrolResultService idb2PatrolResultService;
    @InjectMocks
    private DB2PatrolResultController db2PatrolResultController;

    @BeforeEach
    void setUp() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(db2PatrolResultController).build();
    }

    @Test
    void testPatrolResult() throws Exception {
        PatrolQueryConfig patrolQueryConfig = new PatrolQueryConfig();
        patrolQueryConfig.setItemLevel("0");
        patrolQueryConfig.setStatusType("0");
        String jsonStr = JSONUtil.toJsonStr(patrolQueryConfig);
        this.mockMvc.perform(MockMvcRequestBuilders.get("/dbm/patrolResult/list")
                .param("itemLevel","1")
                .param("statusType","2"))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();
    }
}

controller类代码

	@GetMapping("/list")
    public TableDataInfo<PatrolResult> getRunStatsDataAggs(PatrolQueryConfig patrolQueryConfig) {
        List<PatrolResult> patrolResults = patrolResultService.getPatrolHisResultAggs(patrolQueryConfig);
        return TableDataInfo.build(patrolResults);
    }

3、POST请求(多个参数)

测试类代码

@ExtendWith(MockitoExtension.class)
class AppControllerTest {

    private MockMvc mockMvc;

    @Mock
    private IDB2PatrolResultService idb2PatrolResultService;
    @InjectMocks
    private DB2PatrolResultController db2PatrolResultController;

    @BeforeEach
    void setUp() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(db2PatrolResultController).build();
    }

    @Test
    void testPost() throws Exception {
        PatrolQueryConfig patrolQueryConfig = new PatrolQueryConfig();
        patrolQueryConfig.setItemLevel("0");
        patrolQueryConfig.setStatusType("0");
        String jsonStr = JSONUtil.toJsonStr(patrolQueryConfig);
        this.mockMvc.perform(MockMvcRequestBuilders.post("/dbm/patrolResult/list")
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .content(jsonStr)
                .header(HttpHeaders.ACCEPT,"application/json"))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();
    }
}

controller类代码

	@PostMapping("/list")
    public TableDataInfo<PatrolResult> getRunStatsDataAggs(@RequestBody PatrolQueryConfig patrolQueryConfig) {
        List<PatrolResult> patrolResults = patrolResultService.getPatrolHisResultAggs(patrolQueryConfig);
        return TableDataInfo.build(patrolResults);
    }

三、总结

  • 使用MockMvc可以做到controller层的测试。
  • 在初始化mockMvc的时候:
    (1)如果想测试单个controller
    mockMvc = MockMvcBuilders.standaloneSetup(mockMvcController).build();
    (2)如果想测试所有controller
    mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
相关推荐
Q_192849990632 分钟前
基于Spring Boot的便民医疗服务小程序
spring boot·后端·小程序
开心工作室_kaic2 小时前
springboot548二手物品交易boot代码(论文+源码)_kaic
前端·数据库·vue.js·后端·html5
Java知识日历2 小时前
【内含例子代码】Spring框架的设计模式应用(第二集)
java·开发语言·后端·spring·设计模式
尘浮生4 小时前
Java项目实战II基于微信小程序的家庭大厨(开发文档+数据库+源码)
java·开发语言·数据库·微信小程序·小程序·maven
Java知识技术分享5 小时前
spring boot通过文件配置yaml里面的属性
java·spring boot·后端
Demons_kirit5 小时前
Spring Boot + Redis + Sa-Token
spring boot·redis·后端
一休哥助手5 小时前
深入解析Spring Boot项目的类加载与启动流程
java·spring boot·后端
丁总学Java5 小时前
定义一个名为 MyCache 的 Spring 配置类
java·spring
大叔_爱编程5 小时前
wx011基于springboot+vue+uniapp的机电公司管理信息系统
vue.js·spring boot·uni-app