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?
You have to share the same
RestTemplateobject between service and test code. Otherwise, theMockRestServiceServerwill not recieve the http request. A standard solution is adding aRestTemplate beaninject it in service and test code.