Java 如何在Spring中使用@SpringBootTest运行集成测试
我正在尝试用Spring学习集成测试。因此,我将遵循本教程: 我是这样的一个测试类:Java 如何在Spring中使用@SpringBootTest运行集成测试,java,spring,spring-boot,integration-testing,Java,Spring,Spring Boot,Integration Testing,我正在尝试用Spring学习集成测试。因此,我将遵循本教程: 我是这样的一个测试类: @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class GreetingControllerTest { @Test public void helloTest(){ TestRestTemplate restTempl
@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时,我得到了以下错误:
获取“”请求时出现I/O错误:连接被拒绝;嵌套异常为java.net.ConnectException:连接被拒绝
所以。。。我做错了什么?我需要做什么才能让我的测试顺利进行
注意:如果我运行mvn spring boot:run项目运行正常,我可以使用任何浏览器请求结束点 这是因为测试类中有以下属性:
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
根据spring,它将应用程序绑定到一个随机端口。因此,在发送请求时,应用程序可能无法在端口8080上运行,因此,您会遇到连接被拒绝错误
如果要在特定端口上运行应用程序,则需要删除webEnvironment
属性,并用以下内容注释类:
@IntegrationTest(“server.port=8080”)
另一种方法是获取端口并将其添加到url中,下面是获取端口的代码段:
@Autowired
Environment environment;
String port = environment.getProperty("local.server.port");
如果要执行以下操作,可以将随机端口值自动关联到测试类中的字段:
@LocalServerPort
int port;
但是您可以自动连接restTemplate,并且应该能够将其与相对URI一起使用,而无需知道端口号:
@Autowired
private TestRestTemplate restTemplate;
@Test
public void helloTest(){
Hello hello = restTemplate.getForObject("/hello", Hello.class);
Assert.assertEquals(hello.getMessage(), "ola!");
}
我相信您需要注入testrestmplate
。要么这样,要么您不需要指定端口,因为您使用的是RANDOM\u port
。这只需要一个技巧。发送请求时,而不是启动时,必须使用environment.getProperty(“local.server.port”)
获取端口号。这是因为服务器尚未完成启动。