我正在尝试学习与 Spring 的集成测试。所以我正在学习本教程:
http://www.lucassaldanha.com/unit-and-integration-tests-in-spring-boot/
我很喜欢这样的测试类:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class GreetingControllerTest {
@Test
public void helloTest(){
TestRestTemplate restTemplate = new TestRestTemplate();
Hello hello = restTemplate.getForObject("http://localhost:8080/hello", Hello.class);
Assert.assertEquals(hello.getMessage(), "ola!");
}
}
但是当我mvn install时,我得到这个错误:
“http://localhost:8080/hello”的 GET 请求出现 I/O 错误:连接被拒绝;嵌套异常是 java.net.ConnectException: Connection refused
所以...我做错了什么?我需要做什么才能让我的测试成功?
注意:如果我运行mvn spring-boot:run,项目工作正常,我使用任何浏览器请求端点。
最佳答案
那是因为你的测试类中有以下属性:
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
根据 Spring documentation ,它将应用程序绑定(bind)到一个随机端口。因此,在发送请求时,应用程序可能不会在 端口
8080 上运行,因此您会收到连接被拒绝的错误。
如果您想在特定端口上运行该应用程序,您需要删除 webEnvironment
属性并使用以下注释您的类:
@IntegrationTest("server.port=8080")
另一种方法是获取端口并将其添加到 url 中,下面是获取端口的代码段:
@Autowired
Environment environment;
String port = environment.getProperty("local.server.port");
关于java - 如何使用@SpringBootTest 在 Spring 中运行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42056627/