首页 > 解决方案 > 为什么我的 RestTemple 无法连接到服务器?

问题描述

我正在使用 Springboot 和 Java 8

我有以下网址,与邮递员配合得很好:

http://localhost:8888/gc/goods/getAll

现在我尝试编写一个自动化测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class GCGoodControllerTest 
{
    @Test
    public void getAllGoodsRequest()
    {
        RestTemplate restTemplate = new RestTemplate();
        Object test = restTemplate.getForObject("http://localhost:8888/gc/goods/getAll", Object.class);
    }
}

当 Postman 将所有数据返回给我时,我的测试中出现以下错误:

org.springframework.web.client.ResourceAccessException:“ http://localhost:8888/gc/goods/getAll ”的 GET 请求上的 I/O 错误:连接被拒绝:连接;嵌套异常是 java.net.ConnectException: Connection denied: connect

如何在测试期间正确请求数据?

感谢帮助!

标签: spring-boottestingresttemplate

解决方案


当您的自动化测试运行时,听起来您的服务器没有启动并在端口 8888 上运行。如果你需要测试来启动你的嵌入式服务器,你需要用类似的东西注释测试类

@SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT)

推荐阅读