该版本仍在开发中,尚未被视为稳定。对于最新的稳定版本,请使用 spring-cloud-contract 5.0.0!spring-doc.cadn.net.cn

使用可插拔架构

你可能会遇到合同被定义为其他格式的情况, 例如YAML、RAML或PACT。在这种情况下,你仍然希望享受自动挡的优势 生成测试和存根。你可以添加自己的实现来生成两者 测试和小作品。此外,你可以自定义测试生成方式(例如,你 可以生成其他语言的测试)以及存根生成的方式(例如,你 可以生成其他HTTP服务器实现的存根)。spring-doc.cadn.net.cn

定制合同转换器

ContractConverter接口允许你注册自己的契约实现结构转换器。以下代码列表展示了ContractConverter接口:spring-doc.cadn.net.cn

import java.io.File;
import java.util.Collection;

/**
 * Converter to be used to convert FROM {@link File} TO {@link Contract} and from
 * {@link Contract} to {@code T}.
 *
 * @param <T> - type to which we want to convert the contract
 * @author Marcin Grzejszczak
 * @since 1.1.0
 */
public interface ContractConverter<T> extends ContractStorer<T>, ContractReader<T> {

	/**
	 * Should this file be accepted by the converter. Can use the file extension to check
	 * if the conversion is possible.
	 * @param file - file to be considered for conversion
	 * @return - {@code true} if the given implementation can convert the file
	 */
	boolean isAccepted(File file);

	/**
	 * Converts the given {@link File} to its {@link Contract} representation.
	 * @param file - file to convert
	 * @return - {@link Contract} representation of the file
	 */
	Collection<Contract> convertFrom(File file);

	/**
	 * Converts the given {@link Contract} to a {@link T} representation.
	 * @param contract - the parsed contract
	 * @return - {@link T} the type to which we do the conversion
	 */
	T convertTo(Collection<Contract> contract);

}

你的实现必须定义它应在 转换。 此外,你必须定义如何在双向进行转换。spring-doc.cadn.net.cn

一旦你创建了实现,你必须创建/元-INF/spring.factories在文件中,你必须提供你所属的完全合格姓名 实现。

以下示例展示了一个典型的Spring。工厂文件:spring-doc.cadn.net.cn

org.springframework.cloud.contract.spec.ContractConverter=\
org.springframework.cloud.contract.verifier.converter.YamlContractConverter

使用自定义测试生成器

如果你想生成非 Java 语言的测试,或者你对验证器构建 Java 测试的方式不满意,你可以注册自己的实现。spring-doc.cadn.net.cn

单一测试生成器界面允许你注册自己的实现。 这 以下代码列表显示单一测试生成器接口:spring-doc.cadn.net.cn

import java.nio.file.Path;
import java.util.Collection;

import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties;
import org.springframework.cloud.contract.verifier.file.ContractMetadata;

/**
 * Builds a single test.
 *
 * @since 1.1.0
 */
public interface SingleTestGenerator {

	/**
	 * Creates contents of a single test class in which all test scenarios from the
	 * contract metadata should be placed.
	 * @param properties - properties passed to the plugin
	 * @param listOfFiles - list of parsed contracts with additional metadata
	 * @param generatedClassData - information about the generated class
	 * @param includedDirectoryRelativePath - relative path to the included directory
	 * @return contents of a single test class
	 */
	String buildClass(ContractVerifierConfigProperties properties, Collection<ContractMetadata> listOfFiles,
			String includedDirectoryRelativePath, GeneratedClassData generatedClassData);

	class GeneratedClassData {

		public final String className;

		public final String classPackage;

		public final Path testClassPath;

		public GeneratedClassData(String className, String classPackage, Path testClassPath) {
			this.className = className;
			this.classPackage = classPackage;
			this.testClassPath = testClassPath;
		}

	}

}

同样,你必须提供Spring。工厂文件,例如下面所示的 例:spring-doc.cadn.net.cn

org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
com.example.MyGenerator

使用自定义存根生成器

如果你想为除 WireMock 以外的存根服务器生成存根,你可以插入你自己的实现短根生成器接口。 以下代码列表展示了短根生成器接口:spring-doc.cadn.net.cn

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.cloud.contract.spec.Contract;
import org.springframework.cloud.contract.verifier.file.ContractMetadata;

/**
 * Converts contracts into their stub representation.
 *
 * @param <T> - type of stub mapping
 * @since 1.1.0
 */
public interface StubGenerator<T> {

	/**
	 * @param mapping - potential stub mapping mapping
	 * @return {@code true} if this converter could have generated this mapping stub.
	 */
	default boolean canReadStubMapping(File mapping) {
		return mapping.getName().endsWith(fileExtension());
	}

	/**
	 * @param rootName - root name of the contract
	 * @param content - metadata of the contract
	 * @return the collection of converted contracts into stubs. One contract can result
	 * in multiple stubs.
	 */
	Map<Contract, String> convertContents(String rootName, ContractMetadata content);

	/**
	 * Post process a generated stub mapping.
	 * @param stubMapping - mapping of a stub
	 * @param contract - contract for which stub was generated
	 * @return the converted stub mapping
	 */
	default T postProcessStubMapping(T stubMapping, Contract contract) {
		List<StubPostProcessor> processors = StubPostProcessor.PROCESSORS.stream()
			.filter(p -> p.isApplicable(contract))
			.collect(Collectors.toList());
		if (processors.isEmpty()) {
			return defaultStubMappingPostProcessing(stubMapping, contract);
		}
		T stub = stubMapping;
		for (StubPostProcessor processor : processors) {
			stub = (T) processor.postProcess(stub, contract);
		}
		return stub;
	}

	/**
	 * Stub mapping to chose when no post processors where found on the classpath.
	 * @param stubMapping - mapping of a stub
	 * @param contract - contract for which stub was generated
	 * @return the converted stub mapping
	 */
	default T defaultStubMappingPostProcessing(T stubMapping, Contract contract) {
		return stubMapping;
	}

	/**
	 * @param inputFileName - name of the input file
	 * @return the name of the converted stub file. If you have multiple contracts in a
	 * single file then a prefix will be added to the generated file. If you provide the
	 * {@link Contract#getName} field then that field will override the generated file
	 * name.
	 *
	 * Example: name of file with 2 contracts is {@code foo.groovy}, it will be converted
	 * by the implementation to {@code foo.json}. The recursive file converter will create
	 * two files {@code 0_foo.json} and {@code 1_foo.json}
	 */
	String generateOutputFileNameForInput(String inputFileName);

	/**
	 * Describes the file extension of the generated mapping that this stub generator can
	 * handle.
	 * @return string describing the file extension
	 */
	default String fileExtension() {
		return ".json";
	}

}

同样,你必须提供Spring。工厂文件,例如下面所示的 例:spring-doc.cadn.net.cn

# Stub converters
org.springframework.cloud.contract.verifier.converter.StubGenerator=\
org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter

默认实现是 WireMock stub 生成。spring-doc.cadn.net.cn

你可以提供多个存根生成器的实现。例如,从单个DSL 中,你可以同时生成 WireMock 存根和 Pact 文件。

使用自定义存根滑板

如果你决定使用自定义存根生成,你还需要一个自定义的方式来运行存根,使用你的不同的存根提供者。spring-doc.cadn.net.cn

假设你使用 Moco 来构建存根,并且你写了一个存根生成器,并将存根放进了 JAR 文件中。spring-doc.cadn.net.cn

为了让 Stub Runner 知道如何运行你的 stub,你必须定义一个自定义的HTTP Stub 服务器实现,可能类似于以下示例:spring-doc.cadn.net.cn

import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
import com.github.dreamhead.moco.runner.JsonRunner
import com.github.dreamhead.moco.runner.RunnerSetting
import groovy.transform.CompileStatic
import groovy.util.logging.Commons

import org.springframework.cloud.contract.stubrunner.HttpServerStub
import org.springframework.cloud.contract.stubrunner.HttpServerStubConfiguration

@Commons
@CompileStatic
class MocoHttpServerStub implements HttpServerStub {

	private boolean started
	private JsonRunner runner
	private int port

	@Override
	int port() {
		if (!isRunning()) {
			return -1
		}
		return port
	}

	@Override
	boolean isRunning() {
		return started
	}

	@Override
	HttpServerStub start(HttpServerStubConfiguration configuration) {
		this.port = configuration.port
		return this
	}

	@Override
	HttpServerStub stop() {
		if (!isRunning()) {
			return this
		}
		this.runner.stop()
		return this
	}

	@Override
	HttpServerStub registerMappings(Collection<File> stubFiles) {
		List<RunnerSetting> settings = stubFiles.findAll { it.name.endsWith("json") }
			.collect {
			log.info("Trying to parse [${it.name}]")
			try {
				return RunnerSetting.aRunnerSetting().addStream(it.newInputStream()).
					build()
			}
			catch (Exception e) {
				log.warn("Exception occurred while trying to parse file [${it.name}]", e)
				return null
			}
		}.findAll { it }
		this.runner = JsonRunner.newJsonRunnerWithSetting(settings,
			HttpArgs.httpArgs().withPort(this.port).build())
		this.runner.run()
		this.started = true
		return this
	}

	@Override
	String registeredMappings() {
		return ""
	}

	@Override
	boolean isAccepted(File file) {
		return file.name.endsWith(".json")
	}
}

然后你可以在你的Spring。工厂文件,如下示例显示:spring-doc.cadn.net.cn

org.springframework.cloud.contract.stubrunner.HttpServerStub=\
org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub

现在你可以用Moco跑存根了。spring-doc.cadn.net.cn

如果你没有提供任何实现,则默认的(WireMock)实现被使用。如果你提供多个实现,则使用列表中的第一个实现。

使用自定义存根下载器

你可以通过创建StubDownloaderBuilder界面,如下示例所示:spring-doc.cadn.net.cn

class CustomStubDownloaderBuilder implements StubDownloaderBuilder {

	@Override
	public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
		return new StubDownloader() {
			@Override
			public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
					StubConfiguration config) {
				File unpackedStubs = retrieveStubs();
				return new AbstractMap.SimpleEntry<>(
						new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
								config.getClassifier()), unpackedStubs);
			}

			File retrieveStubs() {
			    // here goes your custom logic to provide a folder where all the stubs reside
			}
		}
	}
}

然后你可以在你的Spring。工厂文件,如下示例显示:spring-doc.cadn.net.cn

# Example of a custom Stub Downloader Provider
org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
com.example.CustomStubDownloaderBuilder

现在你可以选择一个包含存根来源的文件夹。spring-doc.cadn.net.cn

如果你没有提供任何实现,则使用默认的(扫描类路径)。如果你提供stubsMode = StubRunnerProperties.StubsMode.LOCALstubsMode = StubRunnerProperties.StubsMode.REMOTE,使用Aether实现如果提供多个,则使用列表中的第一个实现。

使用 SCM 存根下载器

每当repositoryRoot以SCM协议开始(目前,我们仅支持git://,存根下载器尝试克隆该仓库并将其作为契约的源头生成测试或存根。spring-doc.cadn.net.cn

通过环境变量、系统属性或属性设置在插件或合同仓库配置中,你可以调整下载者的行为。下表描述了可用的 性能:spring-doc.cadn.net.cn

表1。SCM 存根下载器属性

物业类型spring-doc.cadn.net.cn

地产名称spring-doc.cadn.net.cn

描述spring-doc.cadn.net.cn

* git.branch(插件道具)spring-doc.cadn.net.cn

* stubrunner.properties.git.branch(系统道具)spring-doc.cadn.net.cn

* STUBRUNNER_PROPERTIES_GIT_BRANCH(环境道具)spring-doc.cadn.net.cn

主人spring-doc.cadn.net.cn

该查哪个分行spring-doc.cadn.net.cn

* git.username(插件道具)spring-doc.cadn.net.cn

* stubrunner.properties.git.username(系统道具)spring-doc.cadn.net.cn

* STUBRUNNER_PROPERTIES_GIT_USERNAME(环境道具)spring-doc.cadn.net.cn

Git 克隆用户名spring-doc.cadn.net.cn

* git.password(插件道具)spring-doc.cadn.net.cn

* stubrunner.properties.git.password(系统道具)spring-doc.cadn.net.cn

* STUBRUNNER_PROPERTIES_GIT_PASSWORD(环境道具)spring-doc.cadn.net.cn

git克隆密码spring-doc.cadn.net.cn

* git.无尝试(插件道具)spring-doc.cadn.net.cn

* stubrunner.properties.git.no-of-attempts(系统道具)spring-doc.cadn.net.cn

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS(环境道具)spring-doc.cadn.net.cn

10spring-doc.cadn.net.cn

将提交推送到起源spring-doc.cadn.net.cn

* git.尝试间等待(插件道具)spring-doc.cadn.net.cn

* stubrunner.properties.git.wait-between-attempts(系统道具)spring-doc.cadn.net.cn

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS(环境道具)spring-doc.cadn.net.cn

1000spring-doc.cadn.net.cn

推送提交至的尝试之间等待的毫秒数起源spring-doc.cadn.net.cn