2017-08-30 155 views
0

我想爲我的mvc控制器做測試,所以我知道他們工作正常。我會第一時間發佈所有的代碼,然後解釋發生了什麼事:jUnit與Spring MVC返回400而不是200

我的控制器

@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("[email protected]"); 
    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("[email protected]"); 
    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()); 
} 

所以,我想測試控制器創建一個居民。我第一次得到一個錯誤,說「參考是nullpointerexception」,我發現這是因爲居民住在公寓中,而公寓中有一間公寓。在修復這個錯誤我絆倒後「狀態除外< 200>但< 400>」,並在控制檯輸出我得到這個:

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

您的Controller類是否使用RequestMapping(value =「api」)註釋? –

+0

Per MockMvcRequestBuilders,post的第二個參數是uriVars - 零個或多個URI變量 –

+0

它的引發org.springframework.http.converter.HttpMessageNotReadableException,您的依賴關係中是否有jackson api庫,並且是使用JSON批註註釋的Resident類屬性。使用Fiddler檢查請求正文中的內容,看起來你的控制器期望的身體是不一樣的。 –

回答

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()); 
} 
+0

我試過了,但它沒有工作,相反,我現在在做.param(),我能夠填充主體 – SkiiNet

+0

因此,我認爲content()不會在參數 – SkiiNet

+0

@SkiiNet中放入任何東西,你的參數是什麼意思?這對我的作品,但我確實改變了請求映射到包括消耗= {} MediaType.APPLICATION_JSON_UTF8_VALUE的 –

相關問題