用restAssured测试spring boot rest应用程序

klu*_*ubi 18 java rest spring rest-assured spring-boot

我一直在努力解决这个问题.我想使用restAssured来测试我的SpringBoot REST应用程序.

虽然看起来容器旋转得恰到好处,但请放心(其他任何事情似乎都有问题.

我一直得到Connection拒绝例外.

java.net.ConnectException: Connection refused

at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
...
Run Code Online (Sandbox Code Playgroud)

我的考试班:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SizesRestControllerIT {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void test() {
        System.out.println(this.restTemplate.getForEntity("/clothes", List.class));
    }

    @Test
    public void test2() throws InterruptedException {
        given().basePath("/clothes").when().get("").then().statusCode(200);
    }

}
Run Code Online (Sandbox Code Playgroud)

现在对于奇怪的部分,test传递和打印它应该test2是什么,但是得到Connection拒绝例外.

任何想法这个设置有什么问题?

klu*_*ubi 36

我会自己回答这个问题..

在花了额外的时间之后,事实证明TestRestTemplate已经知道并设置了正确的端口.RestAssured不......

有了这个,我得到了以下测试运行没有任何问题.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SizesRestControllerIT {

    @LocalServerPort
    int port;

    @Before
    public void setUp() {
        RestAssured.port = port;
    }

    @Test
    public void test2() throws InterruptedException {
        given().basePath("/clothes").get("").then().statusCode(200);
    }

}
Run Code Online (Sandbox Code Playgroud)

我本来可以发誓我之前尝试过这样做...但我想我确实使用了其他一些注释......


小智 5

基于/sf/users/198674451/回答,并且不为您所做的每个请求设置端口:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = 
SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SizesRestControllerIT {

    @LocalServerPort
    int port;

    @Before
    public void setUp() {
        RestAssured.port = port;
    }

    @Test
    public void test2() throws InterruptedException {
        given().basePath("/clothes").get("").then().statusCode(200);
    }
}
Run Code Online (Sandbox Code Playgroud)