首页 > 解决方案 > Spring Cloud Contract EXPLICIT 和 WEBTESTCLIENT 测试模式

问题描述

我想使用 Spring Cloud Contract 来生成我的合约并验证它们。我想使用 Spring WebFlux 和 Junit5。这是我的控制器:

@RestController
@Slf4j
public class HelloWorldPortRESTAdapter implements HelloWorldPort {

    @GetMapping(value = "/hello-world", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Override
    public Mono<String> helloWorld() {
        return Mono.just("Hello World!");
    }
}

这是云合约 Maven 插件配置:

            <plugin>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <basePackageForTests>com.example.feedproviderapi.contract</basePackageForTests>
                    <testFramework>JUNIT5</testFramework>
                    <testMode>EXPLICIT</testMode>
                </configuration>
            </plugin>

但我不知道基础测试类应该是什么样子。我试过这个:

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BaseTestClass {

    @LocalServerPort
    private int port;

    @BeforeEach
    void setup(){
        RestAssured.baseURI = "http://localhost:" + this.port;
    }

}

当我运行时mvn clean install,它会返回java.net.ConnectException: Connection refused (Connection refused)

然后我将testModemaven 插件中的属性更改为WEBTESTCLIENT并更新BaseTestClass如下:

@ExtendWith(SpringExtension.class)
@SpringBootTest
public class BaseTestClass {

    @Autowired
    WebApplicationContext context;

    @BeforeEach
    void setup(){
        RestAssuredWebTestClient.standaloneSetup(context);
    }

}

当我mvn clean install现在运行时,它再次返回:

You haven't configured a WebTestClient instance. You can do this statically

RestAssuredWebTestClient.mockMvc(..)
RestAssuredWebTestClient.standaloneSetup(..);
RestAssuredWebTestClient.webAppContextSetup(..);

or using the DSL:

given().
        mockMvc(..). ..

顺便说一句,我也尝试过RestAssuredWebTestClient.standaloneSetup(new HelloWorldPortRESTAdapter());BaseTestClass但结果是一样的。

那么我应该如何实现BaseTestClass关于EXPLICITWEBTESTCLIENTtestModes?

标签: spring-webfluxjunit5spring-cloud-contract

解决方案


我已经奋斗了 3 天,以使 RestAssuredWebTestClient 工作。

感谢 llooottt:https ://www.baeldung.com/spring-5-webclient

这就是我能做到的:

@WebFluxTest
public class AnimeControllerIntegrTest{

    WebTestClient testClient;

    @Test
    public void get_RA() {

        testClient = WebTestClient.bindToServer().baseUrl("http://localhost:8080/animes").build();

        RestAssuredWebTestClient
                .given()
                .webTestClient(testClient)

                .when()
                .get()

                .then()
                .statusCode(OK.value())

                .body("name" ,hasItem("paulo"))
        ;
    }

}

推荐阅读