@SpringBootTest 调用url遇到 Connection refused: connect

背景:

 在写单元测试的时候, 希望通过 RestTemplate 来进行接口调用, 代码写法如下

@RunWith(SpringRunner.class)
@SpringBootTest(classes =  DemoApplication.class)
public class DemoApplicationTests {

    @Test
    public void test() {
        String url = "http://localhost:8080/welcome";

        RestTemplate restTemplate = new RestTemplate();
        String result =  restTemplate.getForObject(url, String.class);
        System.out.println(result);

    }

}

发现一直会报错

org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8080/welcome": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)

原因:

默认的@SpringBootTest注解属性webEnvironment是mock类型, 所以调不通

 

改正后:

@RunWith(SpringRunner.class)
@SpringBootTest(classes =  DemoApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplicationTests {

    @Test
    public void test() {
        String url = "http://localhost:8080/welcome";

        RestTemplate restTemplate = new RestTemplate();
        String result =  restTemplate.getForObject(url, String.class);
        System.out.println(result);

    }

}

重点是@SpringBootTest注解, 要设置属性 webEnvironment

=============================

    @Autowired
    TestRestTemplate testRestTemplate;

另外注入TestRestTemplate 时报错, 也是同样的原因

=============================

参考: 

java - Cannot connect to localhost during test execution - Stack Overflow

40.4.4 TestRestTemplate · Spring Boot 中文参考指南 · 看云

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值