【问题标题】:jUnit with Spring MVC returns a 400 instead a 200带有 Spring MVC 的 jUnit 返回 400 而不是 200
【发布时间】:2017-08-31 01:30:43
【问题描述】:

我正在尝试对我的 mvc 控制器进行测试,以便我知道它们工作正常。我会先贴出所有代码,然后解释发生了什么:

我的控制器

@RequestMapping(value ="Residents/create", method=RequestMethod.POST)
public ResponseEntity<Object> createNewResident(@RequestBody Resident 
resident){
    Apartment apartment = apartmentService.findByApartmentId(167);
    resident.setApartment(apartment);
    System.out.println("slack api");

    String requestUrl = "SlackStringThatIChanged" +"&email=" +resident.getEmail() +
    "&first_name=" + resident.getFirstName() + "&last_name=" + resident.getLastName();
    try {
    URL url = new URL(requestUrl);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestMethod("GET");

    //View Slack response
    /*BufferedReader br = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
        System.out.println(line);
    }
    br.close();
    */
    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return ResponseEntity.ok(residentService.createResident(resident) );
}

我的测试方法

@Test//this still has problems with the apartment...
public void createNewResidentTest() throws Exception {

    apartmentComplex = new ApartmentComplex();
    apartmentComplex.setComplexId(1);
    apartmentComplex.setAddress("1234 theAddress");
    apartmentComplex.setEmail("some@email.com");
    apartmentComplex.setName("westerly");
    apartmentComplex.setPhone("8548");
    apartmentComplex.setWebsite("www.serwtet.com");
    apartmentComplex.setPhoto("weewtfsw");


    apartment = new Apartment();
    apartment.setApartmentId(1);
    apartment.setApartmentNumber(101);
    apartment.setCapacity(6);
    apartment.setOccupancy(3);

    List<Apartment> apt = new ArrayList<>();
    apt.add(apartment);
    apartmentComplex.setApartments(apt);


    resident = new Resident();
    resident.setResidentId(1);
    resident.setFirstName("Cool");
    resident.setLastName("Man");
    resident.setEmail("coolman@cool.com");
    resident.setPhone("548791234");
    resident.setSlackId("32f4443rwd");
    resident.setAbout("Yeah boi");
    resident.setApartment(apartment);

    Set<Resident> resLis = new HashSet<Resident>();
    resLis.add(resident);
    apartment.setResidents(resLis);

    mvc.perform(MockMvcRequestBuilders.post("http://localhost:8181/api/Residents/create", resident)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
}

所以,我正在尝试测试创建居民的控制器。我第一次收到一个错误,上面写着“reference is nullpointerexception”,我发现这是因为居民住在公寓里,而公寓大楼里有公寓。修复此错误后,我偶然发现“状态除外 但为 ”,在控制台输出中我得到以下信息:

MockHttpServletRequest:
  HTTP Method = POST
  Request URI = /api/Residents/create
   Parameters = {}
      Headers = {Accept=[application/json]}

Handler:
         Type = com.application.controller.ResidentController
       Method = public org.springframework.http.ResponseEntity<java.lang.Object> com.application.controller.ResidentController.createNewResident(com.application.model.Resident)

Async:
Async started = false
 Async result = null

Resolved Exception:
         Type = org.springframework.http.converter.HttpMessageNotReadableException

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

FlashMap:
   Attributes = null

我真的不知道发生了什么或可能是什么问题。也许我执行测试错误?

请告诉我你有什么想法!谢谢。

【问题讨论】:

  • 您的 Controller 类是否使用 RequestMapping(value="api") 注释?
  • 每个 MockMvcRequestBuilders,post 的第二个参数是 uriVars - 零个或多个 URI 变量
  • 它抛出 org.springframework.http.converter.HttpMessageNotReadableException,你的依赖项中是否有 jackson api 库,并且是用 JSON 注释注释的 Resident 类属性。使用 Fiddler 检查您的请求正文中的内容,似乎正文与您的控制器所期望的不同。
  • 是的,我正在通过 api/* 做每个控制器,@SeanCarroll,你能给我举个 uriVars 的例子吗?我正在阅读文档,但我不明白那里应该有什么。我的 pom 中有 json 依赖项。我使用 post man 来测试控制器,它显示了包含我传递的所有值的 json。
  • 您的路线没有任何 UriVariables,所以不需要去那里。您应该使用 MockHttpServletRequestBuilder 的 content 方法传递您的 json

标签: java spring spring-mvc junit spring-mvc-test


【解决方案1】:

类似下面的内容呢?

@Test//this still has problems with the apartment...
public void createNewResidentTest() throws Exception {

    Resident resident = new Resident();
    // build resident
    // convert to json string
    mvc.perform(MockMvcRequestBuilders.post("/api/Residents/create")
            .contentType(MediaType.APPLICATION_JSON)
            .content(json)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
}

【讨论】:

  • 我试过但没用,相反,我现在正在做 .param() 并且我能够填充正文
  • 所以,我认为 content() 没有在参数中添加任何内容
  • @SkiiNet,你说的参数是什么意思?这对我有用,但我确实更改了请求映射以包含 consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE}
  • .content(json) 未在参数 MockHttpServletRequest 中显示:HTTP Method = POST Request URI = /api/Residents/create Parameters = {} Headers = {Accept=[application/json] }
  • 我不确定它的假设。在我的测试中你是对的,但它仍然适当地填充了 resident 参数
猜你喜欢
  • 2021-06-27
  • 1970-01-01
  • 2020-11-21
  • 2019-03-23
  • 1970-01-01
  • 2012-12-29
  • 2020-02-16
  • 2021-07-28
  • 1970-01-01
相关资源
最近更新 更多