带有Spring MVC的jUnit返回400而不是200

时间:2017-08-30 16:25:01

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

我正在尝试对我的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());
}

所以,我正在尝试测试创建常驻的控制器。我第一次得到一个错误,说&#34;引用是nullpointerexception&#34;我发现这是因为居民住在公寓里,公寓大楼里有公寓。在解决了这个错误之后,我偶然发现&#34;状态除外&lt; 200&gt;但是&lt; 400&gt;&#34;在控制台输出中我得到了这个:

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

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

如果您有任何想法,请告诉我!谢谢。

1 个答案:

答案 0 :(得分:0)

如下所示?

@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());
}
相关问题