模拟返回值为空的SpringJunit

r6vfmomb  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(139)

我是JUnit的新手,这是实际的工作,但我注意到在使用Map<String, Object>的TEST中接收到空值,这是什么原因,如果他们的条件不能为空。有一天我会需要这个。
我所做的是因为Map<String, Object>不能在headers.setAll()中实现,因为它需要Map<String, String>,所以我转换它。

@RestController
public class TestController {

    @GetMapping("/test")
    public String testAuth(@RequestParam String name, @RequestHeader Map<String, Object> head) {

        try {
         String conv =  String.valueOf( head.get("head"));
            return name + " "+ conv ;
        } catch (Exception e) {
            return e.getMessage();
        }

    } 
}

测试

@WebMvcTest(controllers =  TestController.class)
public class ControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testControllerHeader() throws Exception {

        Map<String, Object> headerMap = new HashMap<String, Object>();

          Map<String, String> headObjectToString =  headerMap.entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

          HttpHeaders headers = new HttpHeaders();
          headers.setAll(headObjectToString);

          MvcResult result = mockMvc.perform(MockMvcRequestBuilders
                  .get("/test?name=justin")
                  .headers(headers)
                  .accept(MediaType.APPLICATION_JSON)
                  ).andExpect(status().isOk()).andReturn();

          //i make it error just to see the body
          assertEquals(result.getResponse().getStatus(), 201);

         //this the original
        //assertEquals(result.getResponse().getStatus(), 200);

    }

}

正文= justin null

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /test
       Parameters = {name=[justin]}
          Headers = [Accept:"application/json"]
             Body = null
    Session Attrs = {}

Handler:
             Type = com.mock.TestingMokito.Controller.TestController
           Method = com.mock.TestingMokito.Controller.TestController#testAuth(String, Map)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json", Content-Length:"10"]
     Content type = application/json
             Body = justin null
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
voj3qocg

voj3qocg1#

在测试类中,在将headerMap转换为字符串之前,在headerMap中添加一些数据。

@WebMvcTest(controllers =  TestController.class)
public class ControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testControllerHeader() throws Exception {

        Map<String, Object> headerMap = new HashMap<String, Object>();

        headerMap.put("head",new String("This was the bug"));

        Map<String, String> headObjectToString =  headerMap.entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

        HttpHeaders headers = new HttpHeaders();
        headers.setAll(headObjectToString);

        MvcResult result = mockMvc.perform(MockMvcRequestBuilders
                .get("/test?name=justin")
                .headers(headers)
                .accept(MediaType.APPLICATION_JSON)
                ).andExpect(status().isOk()).andReturn();

        //i make it error just to see the body
        assertEquals(result.getResponse().getStatus(), 201);

        //this the original
        //assertEquals(result.getResponse().getStatus(), 200);

    }

}

相关问题