2016-09-21 17 views
2

私はこのリンクを見ました:How to write a unit test for a Spring Boot Controller endpointユニットテスト - Spring Boot App

私はSpring Boot Controllerのユニットテストを予定しています。私は下のコントローラからメソッドを貼り付けました。私が上記のリンクに記載されているアプローチを使用する場合、私はservice.verifyAccount(要求)にする必要がありますか?コントローラーが指定された形式で要求を受け入れるかどうかをテストし、HTTPステータスコードのテストとは別に指定された形式で応答を返しますか?あなたはポートなどのすべてのサーバー構成を設定してください

@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 

を使用してユニットテストケース を書くことができます

@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

/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)); 
} 
の下に言及したコードを使用します
関連する問題