我有一个Spring Web服务器,当服务接收到请求时会进行外部调用,调用第三方Web API(例如获取Facebook OAuth令牌)。在获取此调用的数据后,它将计算一个响应:
@RestController
public class HelloController {
@RequestMapping("/hello_to_facebook")
public String hello_to_facebook() {
// Ask facebook about something
HttpGet httpget = new HttpGet(buildURI("https", "graph.facebook.com", "/oauth/access_token"));
String response = httpClient.execute(httpget).getEntity().toString();
// .. Do something with a response
return response;
}
}
我正在编写一个集成测试,检查访问我的服务器的URL是否导致了一些预期的结果。然而,我想在本地模拟外部服务器,这样我甚至不需要Internet访问就可以测试所有这些内容。最好的方法是什么?
我是spring的新手,这是我迄今为止所做的。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest({})
public class TestHelloControllerIT {
@Test
public void getHelloToFacebook() throws Exception {
String url = new URL("http://localhost:8080/hello_to_facebook").toString();
//Somehow setup facebook server mock ...
//FaceBookServerMock facebookMock = ...
RestTemplate template = new TestRestTemplate();
ResponseEntity<String> response = template.getForEntity(url, String.class);
assertThat(response.getBody(), equalTo("..."));
//Assert that facebook mock got called
//facebookMock.verify();
}
}
实际的设置更加复杂-我正在进行Facebook oauth登录,所有逻辑都不在控制器中,而是在各种Spring Security对象中。但是我认为测试代码应该是一样的,因为我只是访问URL并期望响应,不是吗?