【问题标题】:Why do my RestTemple not connect to server?为什么我的 RestTemple 无法连接到服务器?
【发布时间】:2019-05-17 07:52:12
【问题描述】:

我正在使用 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: I/O 错误 “http://localhost:8888/gc/goods/getAll”的 GET 请求:连接 拒绝:连接;嵌套异常是 java.net.ConnectException: 连接被拒绝:连接

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

感谢您的帮助!

【问题讨论】:

  • 你能在这里发布完整的堆栈跟踪吗?
  • 感谢您抽出宝贵时间,但@pcoates 已经回答了这个问题!

标签: spring-boot testing resttemplate


【解决方案1】:

请在您的测试类中使用以下注释

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest

@RunWith(SpringJUnit4ClassRunner.class) 告诉 JUnit 使用 Spring 引导运行。 @SpringBootTest 将加载 application.properties 和您需要的所有其他 Spring Boot 内容。

【讨论】:

  • 感谢您的建议,但已经有了。我已经更新了我的帖子。对不起,我之前没有提到它。
【解决方案2】:

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

@SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT)

【讨论】:

    猜你喜欢
    • 2011-10-11
    • 1970-01-01
    • 2015-11-22
    • 2021-09-18
    • 2014-04-28
    • 2018-10-27
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    相关资源
    最近更新 更多