MocMvc 我的测试终于成功了,坚持就是胜利

pom.xml

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-test</artifactId>
4     <scope>test</scope>
5 </dependency>

Controller

复制代码
package com.wangfei.learn;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloWorldController {

    @RequestMapping("/getHello")
    public String getHello(@RequestParam(value = "name") String name){
        return "Hello " + name + "!";
    }
}
复制代码

Test

快速创建测试类:在Controller层,将光标落在类名上,按住alt+enter,选中创建测试,选中相应的方法。

复制代码
package com.wangfei.learn;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

@SpringBootTest
class HelloWorldControllerTest {
    private MockMvc mockMvc;
    // 初始化MockMvc
    @BeforeEach
    void setUp(WebApplicationContext wac) {
        // 方式1:明确指定需要测试的“Controller”类
//        this.mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();

        // 方式2:基于Spring容器进行配置,包含了Spring MVC环境和所有“Controller”类。
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }
    @Test
    void getHello() throws Exception{
        // getHello()方法传递参数
        MvcResult result = this.mockMvc.perform(get("/hello/getHello")
                        .param("name", "王菲")//设置参数,如果参数需要json数据的话,就要改变请求数据类型为相应的
                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)//设置请求数据类型
                        .accept(MediaType.APPLICATION_JSON))//设置返回数据类型
                .andExpect(MockMvcResultMatchers.status().isOk())//检查返回状态
                .andDo(MockMvcResultHandlers.print())//打印返回内容
                .andReturn();//返回数据
        //System.out.println(result.getResponse().getContentAsString());//打印返回的内容,中文可能会乱码,可以保持返回数据类型和请求数据类型一致
    }

}
复制代码

 结果

 

 

 

posted @   新生猿  阅读(112)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示