【发布时间】:2015-06-15 12:05:08
【问题描述】:
我有一个 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 会导致一些预期的结果。但是我想在本地模拟外部服务器,这样我什至不需要互联网访问来测试这一切。最好的方法是什么?
我是春天的新手,这就是我目前所拥有的。
@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 并期望得到响应,不是吗?
【问题讨论】:
标签: spring spring-security spring-boot integration-testing