首先,我认为您误用了合同测试的概念。我想知道为什么拥有这些具体的价值观对你来说至关重要?在合同测试中,您只会对链接包含 URL 和端口的某些值感兴趣。您甚至不会调用该 URL。因此,您很可能应该在更进一步之前改变您的方法。
但是,如果您认为这是唯一的方法,我会就如何解决此问题提出我的意见(尽管我尚未对其进行测试,但它看起来应该可以工作;))。
目前使这一切工作并不容易。一旦这个https://github.com/spring-cloud/spring-cloud-contract/pull/429被合并,在即将发布的 Edgware 版本中将会更容易。
不过,我会尝试想一个解决方法。我们要做的是添加一个转换机制,该机制将在从 WireMock 发送回响应负载之前对其进行修改。我们将需要转换类,并且还需要扩展现有的存根服务机制。
首先,让我们创建一个自定义 WireMock 扩展,它将分析 WireMock 使用的每个映射。我们将只想修改其中包含的saveLink
那个。
class CustomExtension extends ResponseTransformer {
@Override
String getName() {
return "url-transformer";
}
/**
* Transformer that converts the save the way we want it to look like
*/
@Override
Response transform(Request request, Response response, FileSource files, Parameters parameters) {
if (requestRelatedToMyParticularCase(response)) {
String body = "\"{\"saveLink\" : \"http://"+ url.host + ":" + url.port + "/v2/entity/save\"}\"";
return new Response(response.getStatus(), response.getStatusMessage(),
body, response.getHeaders(), response.wasConfigured(), response.getFault(), response.isFromProxy());
}
// if it's not related continue as usual
return response;
}
private boolean requestRelatedToMyParticularCase(Response response) {
// is it related to your particular scenario ?
return response.bodyAsString.contains("saveLink");
}
/**
* We want to apply this transformation for all mappings
*/
@Override
boolean applyGlobally() {
return true
}
}
现在,您可以创建一个实现HttpServerStub
并注册它的类,如下所示 - http://cloud.spring.io/spring-cloud-static/Dalston.SR3/#_custom_stub_runner。WireMockHttpServerStub
它基本上是我们手动添加变压器的更改的副本
public class MyCustomWireMockHttpServerStub implements HttpServerStub {
private static final Logger log = LoggerFactory.getLogger(MyCustomWireMockHttpServerStub.class);
private static final int INVALID_PORT = -1;
private WireMockServer wireMockServer;
@Override
public HttpServerStub start(int port) {
this.wireMockServer = new WireMockServer(myConfig().port(port)
.notifier(new Slf4jNotifier(true)));
this.wireMockServer.start();
return this;
}
private WireMockConfiguration myConfig() {
if (ClassUtils.isPresent("org.springframework.cloud.contract.wiremock.WireMockSpring", null)) {
return WireMockSpring.options()
.extensions(responseTransformers());
}
return new WireMockConfiguration().extensions(responseTransformers());
}
private Extension[] responseTransformers() {
List<Extension> extensions = new ArrayList<>();
extensions.add(defaultResponseTemplateTransformer());
extensions.add(new CustomExtension());
return extensions.toArray(new Extension[extensions.size()]);
}
private ResponseTemplateTransformer defaultResponseTemplateTransformer() {
return new ResponseTemplateTransformer(false, helpers());
}
@Override
public int port() {
return isRunning() ? this.wireMockServer.port() : INVALID_PORT;
}
@Override
public boolean isRunning() {
return this.wireMockServer != null && this.wireMockServer.isRunning();
}
@Override
public HttpServerStub start() {
if (isRunning()) {
if (log.isDebugEnabled()) {
log.debug("The server is already running at port [" + port() + "]");
}
return this;
}
return start(SocketUtils.findAvailableTcpPort());
}
@Override
public HttpServerStub stop() {
if (!isRunning()) {
if (log.isDebugEnabled()) {
log.debug("Trying to stop a non started server!");
}
return this;
}
this.wireMockServer.stop();
return this;
}
@Override
public HttpServerStub registerMappings(Collection<File> stubFiles) {
if (!isRunning()) {
throw new IllegalStateException("Server not started!");
}
registerStubMappings(stubFiles);
return this;
}
@Override public String registeredMappings() {
Collection<String> mappings = new ArrayList<>();
for (StubMapping stubMapping : this.wireMockServer.getStubMappings()) {
mappings.add(stubMapping.toString());
}
return jsonArrayOfMappings(mappings);
}
private String jsonArrayOfMappings(Collection<String> mappings) {
return "[" + StringUtils.collectionToDelimitedString(mappings, ",\n") + "]";
}
@Override
public boolean isAccepted(File file) {
return file.getName().endsWith(".json");
}
StubMapping getMapping(File file) {
try (InputStream stream = Files.newInputStream(file.toPath())) {
return StubMapping.buildFrom(
StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
}
catch (IOException e) {
throw new IllegalStateException("Cannot read file", e);
}
}
private void registerStubMappings(Collection<File> stubFiles) {
WireMock wireMock = new WireMock("localhost", port(), "");
registerDefaultHealthChecks(wireMock);
registerStubs(stubFiles, wireMock);
}
private void registerDefaultHealthChecks(WireMock wireMock) {
registerHealthCheck(wireMock, "/ping");
registerHealthCheck(wireMock, "/health");
}
private void registerStubs(Collection<File> sortedMappings, WireMock wireMock) {
for (File mappingDescriptor : sortedMappings) {
try {
wireMock.register(getMapping(mappingDescriptor));
if (log.isDebugEnabled()) {
log.debug("Registered stub mappings from [" + mappingDescriptor + "]");
}
}
catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Failed to register the stub mapping [" + mappingDescriptor + "]", e);
}
}
}
}
private void registerHealthCheck(WireMock wireMock, String url) {
registerHealthCheck(wireMock, url, "OK");
}
private void registerHealthCheck(WireMock wireMock, String url, String body) {
wireMock.register(
WireMock.get(WireMock.urlEqualTo(url)).willReturn(WireMock.aResponse().withBody(body).withStatus(200)));
}
}