背景:
在写单元测试的时候, 希望通过 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