在我的集成测试中,我尝试使用 Resttemplate 将 Get 请求发送到 MockMvcBuilders 创建的虚拟服务器。但是我得到了一个错误:
I/O error on GET request for
"http://localhost:8080/test"
:Connection refused:
(在函数 testAccess() 中,url 为 "http://localhost:8080/test"
)。我的代码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@IntegrationTest("server.port=8080")
public class MyTest {
private MockMvc mockMvc = null;
@Autowired
private WebApplicationContext context;
@Value("${server.port}")
private int port;
@Autowired
private MyController myController;
@Before
public void setUp(){
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.build();
}
@Test
public void testAccess() throws Exception{
RestTemplate restTemplate=new RestTemplate();
String url="http://localhost:8080/test";
try{
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
}
catch(ResourceAccessException ex){
System.out.println(ex.getMessage());
}
}
@Controller
public static class MyController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public @ResponseBody String access() {
return "OK";
}
}
}
最佳答案
我的做法是这样的: 首先,根据您在应用程序中使用的实际 RestTemplate 创建一个模拟服务器
@Before
public void setup() throws Exception {
mockServer = MockRestServiceServer.createServer(myService.restTemplate);
}
然后您定义该请求将如何工作:
mockServer.expect(requestTo("http://localhost:8080/myrestapi"))
.andExpect(method(HttpMethod.POST))
.andRespond(withSuccess("{ success: true }", MediaType.APPLICATION_JSON));
最后,您在应用程序中调用该方法,该方法将使用该 RestTemplate 触发对该 url 的调用:
@Test
public void testThis() throws Exception {
myService.somethingThatCallsMyRestApi(parameters);
}
这将使您的测试正常工作,就像有一个服务器已启动并正在运行来处理请求一样。 在您的示例中使用它是没有意义的,因为您将测试您是否正确构建了测试,而不是实际应用程序中的其他内容。
这样做的问题是您无法测试动态响应。我的意思是,就我而言,我调用的方法每次调用时都会生成不同的数据,然后将其发送到模拟服务器,然后验证响应是否以某种非常特定的方式匹配。我还没有找到解决方案,但是如果您要发送和接收的数据之前是已知的(在大多数情况下),那么使用它不会有任何问题。
关于java - Spring 集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27004551/