2016-09-21 146 views
2

我看了看這個鏈接:How to write a unit test for a Spring Boot Controller endpoint單元測試 - 春季啓動應用

我打算進行單元測試我的春節,啓動控制器。我從下面的控制器粘貼了一個方法。當我使用上面鏈接中提到的方法時,我會不會撥打電話service.verifyAccount(請求)?我們只是測試控制器是否接受指定格式的請求,並返回除了測試HTTP狀態代碼之外的指定格式的響應?

@RequestMapping(value ="verifyAccount", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE) 
public ResponseEntity<VerifyAccountResponse> verifyAccount(@RequestBody VerifyAccountRequest request) { 

    VerifyAccountResponse response = service.verifyAccount(request); 

    return new ResponseEntity<VerifyAccountResponse>(response, HttpStatus.OK); 
} 
+1

It取決於你是否嘲笑服務對象。如果你沒有嘲笑,它會打電話給服務。 – notionquest

+0

謝謝@notionquest。 MockMvc的目的是什麼,如果我不使用模擬對象,我的所有依賴項是否會通過使用其他文章中的代碼(接受的答案)來注入? –

+0

也許這篇文章http://stackoverflow.com/questions/32223490/are-springs-mockmvc-used-for-unit-testing-or-integration-testing有助於回答你的「MockMvc的目的是什麼」的問題。 –

回答

0

可以使用

@RunWith(SpringJUnit4ClassRunner.class) 
    // Your spring configuration class containing the        
    @EnableAutoConfiguration 
    // annotation 
    @SpringApplicationConfiguration(classes = Application.class) 
    // Makes sure the application starts at a random free port, caches it   throughout 
    // all unit tests, and closes it again at the end. 
    @IntegrationTest("server.port:0") 
    @WebAppConfiguration 

確保您配置諸如端口的所有服務器配置編寫單元測試用例 /URL

@Value("${local.server.port}") 
private int port; 


private String getBaseUrl() { 
    return "http://localhost:" + port + "/"; 
} 

然後使用下面

 protected <T> ResponseEntity<T> getResponseEntity(final String  
    requestMappingUrl, final Class<T> serviceReturnTypeClass, final Map<String, ?>  
    parametersInOrderOfAppearance) { 
    // Make a rest template do do the service call 
    final TestRestTemplate restTemplate = new TestRestTemplate(); 
    // Add correct headers, none for this example 

    final HttpEntity<String> requestEntity = new HttpEntity<String>(new  
    HttpHeaders()); 
    // Do a call the the url 
    final ResponseEntity<T> entity = restTemplate.exchange(getBaseUrl() +  
    requestMappingUrl, HttpMethod.GET, requestEntity, serviceReturnTypeClass,  
    parametersInOrderOfAppearance); 
    // Return result 
    return entity; 
    } 

@Test 
public void getWelcomePage() { 
    Map<String, Object> urlVariables = new HashMap<String, Object>(); 
    ResponseEntity<String> response = getResponseEntity("/index",  
    String.class,urlVariables); 

    assertTrue(response.getStatusCode().equals(HttpStatus.OK)); 
} 
提到碼