Skip to content

Instantly share code, notes, and snippets.

@jonashackt
Created May 11, 2015 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonashackt/9ac574dcb3d8a8749c78 to your computer and use it in GitHub Desktop.
Save jonashackt/9ac574dcb3d8a8749c78 to your computer and use it in GitHub Desktop.
REST Mocktest with Spring MockRestServiceServer and RestTemplate
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes=Application.class)
@WebAppConfiguration
public class TarifrechnerTest {
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
@Before
public void setUp() {
restTemplate = new RestTemplate();
/*
* Diese Klasse testet die REST-API des VNETs per Clientseitigem Mock
*/
mockServer = MockRestServiceServer.createServer(restTemplate);
}
@Test
public void verifyCallTarifrechnerRequest() throws BusinessException {
//Given
Request request = WeatherMock.createRequest();
String url = "/myKewlResource";
Response gemockterResponse = WeatherMock.createSbrResponse();
mockServer
.expect(requestTo(url))
.andExpect(method(HttpMethod.POST))
// Der Response wird ausgemockt, deshalb erzeugen wir hier einen Dummy-Response
.andRespond(withSuccess(Util.map2JsonString(gemockterResponse), MediaType.APPLICATION_JSON));
//When
restTemplate.postForObject(url, request, Response.class);
//Then
mockServer.verify();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment