2016-09-21 126 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)); 
} 
提到码