controller层单元测试

 @SpringBootTest
class UserTest{
    @Autowired
    WebApplicationContext webApplicationContext;

    private static final String baseUrl = "/user";
    private MockMvc mvc;
    private HttpHeaders httpHeaders;
    private RequestBuilder request;
    /**初始化测试环境*/
    @BeforeEach
    public void before(){
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        MultiValueMap<String, String> headMap = new LinkedMultiValueMap<>();
        headMap.add("Authorization", "e8a902c11e4e5eadeafd0e6fc5fc97c1");
        headMap.add("Content-Type", "application/json; charset=utf-8");

        httpHeaders = new HttpHeaders();
        httpHeaders.addAll(headMap);
        request = null;
    }

    /**接口返回结果*/
    @AfterEach
    public void after() throws Exception {
        ResultActions resultActions = mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));

        MockHttpServletResponse response = resultActions.andReturn().getResponse();
        response.setCharacterEncoding("UTF-8");

        resultActions.andDo(print());
    }
/** 测试传入参数*/
 @Test
    void user() {
        request = MockMvcRequestBuilders.get(baseUrl + "/user")
                .param("id", "1")
                .param("name", "admin")
                .param("password","123456")
                .headers(httpHeaders);
    }
/** 测试传入的是对象*/
   @Test
    void user() {
        Map<String,Object>map = new HashMap<>();
        map.put("id","1");
        map.put("name","admin");
        map.put("password","123456");
        request = MockMvcRequestBuilders.post(baseUrl + "/user")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content(JSONObject.toJSONString(map))
                .headers(httpHeaders);
    }
}

Java中,Controller是负责处理客户端请求并返回响应的级。要进行Controller单元测试,可以使用一些流行的测试框架,例如JUnit或Mockito。 下面是一个简单的示例,演示如何进行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.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @WebMvcTest(YourController.class) // 替换为你的Controller类名 public class YourControllerTest { @Autowired private MockMvc mockMvc; @MockBean private YourService yourService; // 替换为你的Controller所依赖的Service类 @Test public void testYourController() throws Exception { // 构造模拟请求,并设置请求参数和请求类型 mockMvc.perform(MockMvcRequestBuilders.get("/your-endpoint") .param("param1", "value1") .param("param2", "value2") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().json("expected-response-json")); // 验证期望的响应 } } ``` 在上述示例中,我们使用了`@WebMvcTest`注解来指定要测试的Controller类。使用`@MockBean`注解来模拟所依赖的Service类,以便进行单元测试。然后,使用`mockMvc.perform`方法构造模拟请求,并使用`andExpect`方法来验证响应的状态码和内容。 请注意,这只是一个简单的示例,实际的单元测试可能需要更多的配置和验证步骤,具体取决于你的应用程序需求和测试目标。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值