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

Lea*_*ira 3 java spring integration-testing spring-boot

我正在尝试使用 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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我mvn install,我收到此错误:

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

所以......我做错了什么?我需要做什么才能使我的测试工作?

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

Ros*_*atl 6

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

@LocalServerPort
int port;
Run Code Online (Sandbox Code Playgroud)

但是您可以自动装配restTemplate,并且您应该能够将其与相对URI一起使用,而无需知道端口号:

@Autowired
private TestRestTemplate restTemplate;

@Test
public void helloTest(){    
    Hello hello = restTemplate.getForObject("/hello", Hello.class);
    Assert.assertEquals(hello.getMessage(), "ola!");
}
Run Code Online (Sandbox Code Playgroud)


Dar*_*hta 5

这是因为您的测试类中有以下属性:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)

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

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

@IntegrationTest("server.port=8080")

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

@Autowired
Environment environment;

String port = environment.getProperty("local.server.port");
Run Code Online (Sandbox Code Playgroud)