简体   繁体   English

使用 restAssured 测试 spring 启动 rest 应用程序

[英]testing spring boot rest application with restAssured

I've been struggling with this for some time now.我已经为此苦苦挣扎了一段时间。 I'd like to use restAssured to test my SpringBoot REST application.我想使用 restAssured 来测试我的 SpringBoot REST 应用程序。

While it looks like container spins up properly, rest assured (and anything else seems to have problems reaching out to it.虽然看起来容器正常旋转,但 rest 保证(其他任何东西似乎都无法接触到它。

All the time I'm getting Connection refused exception.我一直收到 Connection refused 异常。

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)
...

my test class:我的测试 class:

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

}

and now for the weird part, test passes and prints what it should, but test2 is getting Connection refused exception.现在对于奇怪的部分, test通过并打印它应该打印的内容,但是test2正在获取 Connection refused 异常。

Any ideas what is wrong with this setup?任何想法这个设置有什么问题?

I'll answer this question myself..这个问题我自己来回答。。

After spending additional amount of time on it it turned out that TestRestTemplate already knows and sets proper port.在花费了额外的时间之后,结果证明TestRestTemplate已经知道并设置了正确的端口。 RestAssured does not...安心不...

With that I got to a point where below test runs without any issues.有了这个,我到了下面的测试运行没有任何问题的地步。

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

}

I could have sworn I tried doing it this way previously... But I guess I did use some other annotations with this...我可以发誓我以前尝试过这样做......但我想我确实使用了其他一些注释......

Based on https://stackoverflow.com/users/2838206/klubi answer and to not set the port for every request that you make:基于https://stackoverflow.com/users/2838206/klubi答案,并且不要为您发出的每个请求设置端口:

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

are you running on some non-standard port may be?您是否在某些非标准端口上运行? have you tried this in your你有没有在你的

@Before public static void init(){ RestAssured.baseURI = "http://localhost"; // replace as appropriate RestAssured.port = 8080; }

I'd recommend to use @WebMvcTest for that case, all you need is to have rest assured mock mvc dependency:我建议在这种情况下使用@WebMvcTest ,您只需要放心模拟 mvc 依赖项:

<dependency>
            <groupId>com.jayway.restassured</groupId>
            <artifactId>spring-mock-mvc</artifactId>
            <version>${rest-assured.version}</version>
            <scope>test</scope>
</dependency>

Using of @SpringBootTest to test just a controller is overhead, all redundant beans, like @Component , @Service , etc, will be created and a full HTTP server will be started.使用@SpringBootTest来测试一个控制器是开销,所有冗余 bean,如@Component@Service等,将被创建,一个完整的 HTTP 服务器将被启动。 For more details: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests ;更多详情: https : //docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests

  @RunWith(SpringRunner.class)
  @WebMvcTest(value = SizesRestController.class)
  public class SizesRestControllerIT {

     @Autowired
     private MockMvc mvc;

     @Before
     public void setUp() {
        RestAssuredMockMvc.mockMvc(mvc);
     }

     @Test
     public void test() {
        RestAssuredMockMvc.given()
           .when()
           .get("/clothes")
           .then()
           .statusCode(200);
        // do some asserts
     }
 }

It looks like you are trying to write an integration test for a Spring Web App.看起来您正在尝试为 Spring Web App 编写集成测试。 REST-assured Support for Spring MockMvc on Baeldung has information on how to do this. REST-assured Support for Spring MockMvc on Baeldung提供了有关如何执行此操作的信息。

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

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void initialiseRestAssuredMockMvcWebApplicationContext() {
        RestAssuredMockMvc.webAppContextSetup(webApplicationContext);
    }

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

What is not mentioned in Baeldung is the static imports change for Spring. Baeldung 中没有提到的是 Spring 的静态导入更改。 REST-Assured Docs on Bootstrapping Spring 关于 Bootstrapping Spring 的 REST-Assured 文档
Import issues mentioned in another StackOverflow另一个 StackOverflow 中提到的导入问题

Make sure you use:确保您使用:

import static io.restassured.module.mockmvc.RestAssuredMockMvc.*;
import static io.restassured.module.mockmvc.matcher.RestAssuredMockMvcMatchers.*;

Do not use with Spring:不要与 Spring 一起使用:

import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;

Using the wrong imports can cause the connection refused exception.使用错误的导入会导致连接被拒绝异常。

Simply:简单地说:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.DEFINED_PORT)
public class CommonScenarioTest {

    @BeforeClass
    public static void setup() {
        RestAssured.baseURI = "http://localhost/foo";
        RestAssured.port = 8090;
    }

I had the same issue, The server was running the App on the the port 34965 (not 8080).我遇到了同样的问题,服务器在端口 34965(不是 8080)上运行应用程序。

This solved my problem :这解决了我的问题:

@Autowired
ServerProperties serverProperties;

@Autowired
Environment environment;

public String getPath() {
    final int port = environment.getProperty("local.server.port", Integer.class);

    return "http://localhost:" + port;
}

@Before
public void setUp() throws Exception {
    RestAssured.baseURI = getPath();
}

@Test
public void testResponse(){
    response = get("/books");
}

I got this same error when I called RestAssured from the @BeforeAll static JUnit method, so I made it non static by adding the @TestInstance(TestInstance.Lifecycle.PER_CLASS) annotation当我从@BeforeAll static JUnit 方法调用 RestAssured 时,我遇到了同样的错误,所以我通过添加@TestInstance(TestInstance.Lifecycle.PER_CLASS)注释使其成为非 static

@BeforeAll
public void setUp() {

    accessToken = getAuthorizationToken();
    Util.deleteAllFromPassThroughCourseWorkList(accessToken);
}

instead of代替

@BeforeAll
public static void setUp() {

    accessToken = getAuthorizationToken();
    Util.deleteAllFromPassThroughCourseWorkList(accessToken);
}

Got the idea from here这里得到的想法

Passing "/clothes" as parameter to get() method should resolve the issue"/clothes"作为参数传递给 get() 方法应该可以解决问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM