0

I would test a service method which has a remote call to another server. This remote call is made by restTemplate.

This is part of my code

    .....
    @Mock
    private RestTemplate restTemplate;

    private MockRestServiceServer server;

    private static String enpointSMS = "http://46.252.156.83:8454/sms";


    @Before
    public void setup() throws Exception {

         .....
        MockitoAnnotations.initMocks(this);

        ReflectionTestUtils.setField(campaignService, "sendSmsEndpointUrl", enpointSMS);

        server = MockRestServiceServer.createServer(restTemplate);
        .....
    }


     @Test
     public void myTest(){
      ......
        server.expect(requestTo(enpointSMS))
            .andExpect(method(POST))
            .andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));

     ......
        verify(mock, times(1)).method1(any(Foo.class));
        verify(mock, times(1)).method2(any(Foo.class));
        server.verify();

     }

All works for verify of mockito but server.verify() get me an error

java.lang.AssertionError: Further request(s) expected leaving 1 unsatisfied expectation(s). 0 request(s) executed.

I can't understand reason, may be I can't use this to mock remote call? If I remove expectation of server (MockRestServiceServer) all works fine.

Any suggestions for this?

Claudio Pomo
  • 2,392
  • 7
  • 42
  • 71
  • Could you also post the interactions to `mock` ? – Ruben Jun 05 '17 at 12:58
  • Could you verify your service call `restTemplate` to make http request? Because the error message says it didn't get any http request. – Beck Yang Jun 06 '17 at 03:32
  • @beckyang yeah! Ok in this way works. However I completely don't understand way with mockrestserverviceserver it doesn't work – Claudio Pomo Jun 06 '17 at 06:13
  • A good choose is tracing the call using the debugger. If your serivce does make http request, `MockRestServiceServer$RequestMatcherClientHttpRequestFactory.createRequestInternal(URI, HttpMethod)` will be invoked... – Beck Yang Jun 06 '17 at 06:22
  • @beckyang my service uses `reatTemplate.postForObject(...)` and endpoint of request and method match between from test and production code, however, as I saw above, test fail. Anyway with stub of restTemplate my goal is satisfied – Claudio Pomo Jun 06 '17 at 09:40
  • @beckyang my service uses `reatTemplate.postForObject(...)` and endpoint of request and method match between from test and production code, however, as I saw above, test fail. Anyway with stub of restTemplate my goal is satisfied – Claudio Pomo Jun 06 '17 at 09:40

1 Answers1

1

You have to share the same RestTemplate object between service and test code. Otherwise, the MockRestServiceServer will not recieve the http request. A standard solution is adding a RestTemplate bean inject it in service and test code.

@Autowired
private RestTemplate restTemplate;

private MockRestServiceServer server;
//...
Beck Yang
  • 3,004
  • 2
  • 21
  • 26