如何使用@SpringBootTest 运行 Spring 中的集成测试

How to run a integration test in Spring with @SpringBootTest

我正在尝试学习 Spring 的集成测试。所以我正在学习本教程:

http://www.lucassaldanha.com/unit-and-integration-tests-in-spring-boot/

我正在接受这样的测试Class:

@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 时,我得到这个错误:

I/O 对“http://localhost:8080/hello”的 GET 请求出错:连接被拒绝;嵌套异常是 java.net.ConnectException:连接被拒绝

所以...我做错了什么?我需要做什么才能让我的测试成功?

注:如果我运行mvnspring-boot:运行 该项目工作正常,我使用任何浏览器请求终点。

那是因为你的测试 属性 class:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

根据spring documentation,它将应用程序绑定到一个随机端口。因此,在发送请求时,应用程序可能不会在 port 8080 上 运行ning,因此,您会收到连接被拒绝的错误。

如果您想 运行 特定端口上的应用程序,您需要删除 webEnvironment 属性 并使用以下注释 class:

@IntegrationTest("server.port=8080")

另一种方法是获取端口并将其添加到 url,下面是获取端口的代码片段:

@Autowired
Environment environment;

String port = environment.getProperty("local.server.port");

如果需要,您可以将随机端口值自动连接到测试中的字段 class:

@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!");
}