自定义模式
| 此模式是实验性的,未来可能会有所改变。 |
Spring Cloud Contract 允许您提供自己的 org.springframework.cloud.contract.verifier.http.HttpVerifier 自定义实现。这样,您可以使用任何您想要的客户端来发送和接收请求。Spring Cloud Contract 中的默认实现是 OkHttpHttpVerifier,它使用 OkHttp3 http 客户端。
首先,将 testMode 设置为 CUSTOM
testMode = 'CUSTOM'
以下示例展示了一个生成的测试
import com.example.BeerRestBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.contract.verifier.http.HttpVerifier;
import org.springframework.cloud.contract.verifier.http.Request;
import org.springframework.cloud.contract.verifier.http.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
import static org.springframework.cloud.contract.verifier.http.Request.given;
public class RestTest extends BeerRestBase {
@Autowired HttpVerifier httpVerifier;
@Test
public void validate_shouldGrantABeerIfOldEnough() throws Exception {
// given:
Request request = given()
.post("/beer.BeerService/check")
.scheme("HTTP")
.protocol("h2_prior_knowledge")
.header("Content-Type", "application/grpc")
.header("te", "trailers")
.body(fileToBytes(this, "shouldGrantABeerIfOldEnough_request_PersonToCheck_old_enough.bin"))
.build();
// when:
Response response = httpVerifier.exchange(request);
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/grpc.*");
assertThat(response.header("grpc-encoding")).isEqualTo("identity");
assertThat(response.header("grpc-accept-encoding")).isEqualTo("gzip");
// and:
assertThat(response.getBody().asByteArray()).isEqualTo(fileToBytes(this, "shouldGrantABeerIfOldEnough_response_Response_old_enough.bin"));
}
}
以下示例展示了一个相应的基类
@SpringBootTest(classes = BeerRestBase.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class BeerRestBase {
@Configuration
@EnableAutoConfiguration
static class Config {
@Bean
ProducerController producerController(PersonCheckingService personCheckingService) {
return new ProducerController(personCheckingService);
}
@Bean
PersonCheckingService testPersonCheckingService() {
return argument -> argument.getAge() >= 20;
}
@Bean
HttpVerifier httpOkVerifier(@LocalServerPort int port) {
return new OkHttpHttpVerifier("localhost:" + port);
}
}
}