2017-09-01 6 views
0

私はMockitoテストを作成しようとしていますが、実際に残りのAPIを呼び出しているのです、クライアント側の休憩サービスを模擬する方法

1)コントローラクラス

public void sendData(ID id, String xmlString, Records record) throws ValidationException{ 
     ClientHttpRequestFactory requestFactory = new 
       HttpComponentsClientHttpRequestFactory(HttpClients.createDefault()); 
     RestTemplate restTemplate = new RestTemplate(requestFactory); 

     List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); 
     messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); 

     restTemplate.setMessageConverters(messageConverters); 

     MultiValueMap<String,String> header = new LinkedMultiValueMap<>(); 
     header.add("x-api-key",api_key); 
     header.add("Content-Type",content_type); 
     header.add("Cache-Control",cache_control); 
     HttpEntity<String> request = new HttpEntity<>(xmlString, header); 

     try { 
      restTemplate.postForEntity(getUri(id,record), request, String.class); 
     }catch (RestClientResponseException e){ 
      throw new ValidationException("Error occurred while sending a file to some server "+e.getResponseBodyAsString()); 
     } 

    } 

2)Testクラス

 @RunWith(MockitoJUnitRunner.class) 
     public class Safe2RestControllerTest { 
      private MockRestServiceServer server; 
      private RestTemplate restTemplate; 
      private restControllerClass serviceToTest; 

     @Before 
     public void init(){ 
     //some code for initialization of the parameters used in controller class  

     this.server = MockRestServiceServer.bindTo(this.restTemplate).ignoreExpectOrder(true).build(); 
     } 

      @Test 
      public void testSendDataToSafe2() throws ValidationException, URISyntaxException { 

      //some code here when().then() 

      String responseBody = "{\n" + 
         " \"responseMessage\": \"Validation succeeded, message 
          accepted.\",\n" + 
         " \"responseCode\": \"SUCCESS\",\n" + 
         " 2\"responseID\": \"627ccf4dcc1a413588e5e2bae7f47e9c::0d86869e-663a-41f0-9f4c-4c7e0b278905\"\n" + 
         "}"; 

      this.server.expect(MockRestRequestMatchers.requestTo(uri)) 
      .andRespond(MockRestResponseCreators.withSuccess(responseBody, 
      MediaType.APPLICATION_JSON)); 

      serviceToTest.sendData(id, xmlString, record); 
      this.server.verify(); 
      } 
     } 

どのように私は先に行く必要がありますが、それをからかうの、任意の提案をいただければ幸いです。

答えて

1

SpringのMVCテスト装置でこれを簡単に行うことができます。詳細については

@RunWith(SpringRunner.class) 
@WebMvcTest(controllers = YourController.class) 
public class YourControllerTest { 

    @Autowired 
    private MockMvc mockMvc; 

    @Test 
    public void testSendDataToSafe2() throws Exception { 
     // prepare e.g. create the requestBody 

     MvcResult mvcResult = mockMvc.perform(post(uri).contentType(MediaType.APPLICATION_JSON).content(requestBody)) 
      .andExpect(status().isOk()) 
      .andReturn(); 

     Assert.assertEquals(responseBody, mvcResult.getResponse().getContentAsString()); 
    } 
} 

hereおよび/またはhere自動構成されたSpring MVCのはをテストする」というタイトルのセクション「ユニットがをテストします」というタイトルのセクションを参照してください。

あなたの質問には、「問題はまだ実際の残りのAPIが呼び出されています」ということですので、コントローラを呼び出すことに加えて、テストコンテキストであることに加えて、そのコントローラの動作。具体的には、コントローラで使用されているRestTemplateインスタンスをモックしたいとします。その場合、RestTemplateインスタンスが@Autowiredクラスメンバであるようにコントローラの実装を変更する必要があります。そして、あなたはそうのようなテストケースにはそのためのモックを宣言します:

@RunWith(SpringRunner.class) 
@WebMvcTest(controllers = YourController.class) 
public class YourControllerTest { 

    @Autowired 
    private MockMvc mockMvc; 

    @MockBean 
    private RestTemplate restTemplate; 

    @Test 
    public void testSendDataToSafe2() throws Exception { 
     // prepare e.g. create the requestBody 

     // tell your mocked RestTemplate what to do when it is invoked within the controller 
     Mockito.when(restTemplate.postForEntity(..., ..., ...)).thenReturn(...); 

     MvcResult mvcResult = mockMvc.perform(post(uri).contentType(MediaType.APPLICATION_JSON).content(requestBody)) 
      .andExpect(status().isOk()) 
      .andReturn(); 

     Assert.assertEquals(responseBody, mvcResult.getResponse().getContentAsString()); 
    } 
} 

上記のコードはspring-test:4.3.10.RELEASE有効です。

+0

これは: '.andExpect(status()。isOk())'は、HTTPステータスを確認するための便利なメソッドです。それを削除し、状態を明示的にチェックすることができます。 – glytching

+0

はい、私はそれが働いたと思います。ありがとう@glitch .. – tyro

+0

私はまだそれがどのようにブレークポイントで停止していないと私もそこにブレークポイントを持っているコントローラクラスで停止していないことを確認するために、それをデバッグしようとしているときに、質問があります実際にテスト。これを理解していない – tyro

関連する問題