TDD test spring service with remote call

760 Views Asked by At

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?

1

There are 1 best solutions below

0
Beck Yang On

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;
//...