Maven Project

Adding the Maven Plugin

若要添加 Spring Cloud Contract BOM,在您的 pom.xml 文件中包含以下部分:

To add the Spring Cloud Contract BOM, include the following section in your pom.xml file:

Unresolved directive in maven-project.adoc - include::{standalone_samples_path}/http-server/pom.xml[]

接下来,按以下方式添加 Spring Cloud Contract Verifier Maven 插件:

Next, add the Spring Cloud Contract Verifier Maven plugin, as follows:

Unresolved directive in maven-project.adoc - include::{standalone_samples_path}/http-server/pom.xml[]

您可以在spring-cloud-contract-maven-plugin/index.html[Spring Cloud Contract Maven 插件文档]中阅读更多内容。

You can read more in the spring-cloud-contract-maven-plugin/index.html[Spring Cloud Contract Maven Plugin Documentation].

有时,无论选择什么 IDE,您都可以看到 target/generated-test-source 文件夹在 IDE 的类路径中不可见。为确保它始终存在,您可以向您的 pom.xml 添加以下条目

Sometimes, regardless of the picked IDE, you can see that the target/generated-test-source folder is not visible on the IDE’s classpath. To ensure that it is always there, you can add the following entry to your pom.xml

<plugin>
	<groupId>org.codehaus.mojo</groupId>
	<artifactId>build-helper-maven-plugin</artifactId>
	<executions>
		<execution>
			<id>add-source</id>
			<phase>generate-test-sources</phase>
			<goals>
				<goal>add-test-source</goal>
			</goals>
			<configuration>
				<sources>
					<source>${project.build.directory}/generated-test-sources/contracts/</source>
				</sources>
			</configuration>
		</execution>
	</executions>
</plugin>

Maven and Rest Assured 2.0

默认情况下,Rest Assured 3.x 被添加到类路径。但是,您可以通过以下方式将 RestAssured 2.x 添加到插件类路径来使用它:

By default, Rest Assured 3.x is added to the classpath. However, you can use Rest Assured 2.x by adding it to the plugins classpath, as follows:

<plugin>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
    <version>${spring-cloud-contract.version}</version>
    <extensions>true</extensions>
    <configuration>
        <packageWithBaseClasses>com.example</packageWithBaseClasses>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-contract-verifier</artifactId>
            <version>${spring-cloud-contract.version}</version>
        </dependency>
        <dependency>
           <groupId>com.jayway.restassured</groupId>
           <artifactId>rest-assured</artifactId>
           <version>2.5.0</version>
           <scope>compile</scope>
        </dependency>
        <dependency>
           <groupId>com.jayway.restassured</groupId>
           <artifactId>spring-mock-mvc</artifactId>
           <version>2.5.0</version>
           <scope>compile</scope>
        </dependency>
    </dependencies>
</plugin>

<dependencies>
    <!-- all dependencies -->
    <!-- you can exclude rest-assured from spring-cloud-contract-verifier -->
    <dependency>
       <groupId>com.jayway.restassured</groupId>
       <artifactId>rest-assured</artifactId>
       <version>2.5.0</version>
       <scope>test</scope>
    </dependency>
    <dependency>
       <groupId>com.jayway.restassured</groupId>
       <artifactId>spring-mock-mvc</artifactId>
       <version>2.5.0</version>
       <scope>test</scope>
    </dependency>
</dependencies>

这样一来,插件会自动看到 Rest Assured 2.x 在类路径中,并相应地修改导入。

That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath and modifies the imports accordingly.

Using Snapshot and Milestone Versions for Maven

若要使用 Snapshot 和 Milestone 版本,您必须将以下部分添加到您的 pom.xml

To use Snapshot and Milestone versions, you have to add the following section to your pom.xml:

Unresolved directive in maven-project.adoc - include::{standalone_samples_path}/http-server/pom.xml[]

Adding stubs

默认情况下,Spring Cloud Contract Verifier 在 src/test/resources/contracts 目录中查找存根。包含存根定义的目录被视为类名,而每个存根定义被视为一个测试。我们假设其中至少包含一个用于作为测试类名的目录。如果有多层的嵌套目录,则会使用除最后一级目录外的所有目录作为包名称。考虑以下结构:

By default, Spring Cloud Contract Verifier looks for stubs in the src/test/resources/contracts directory. The directory containing stub definitions is treated as a class name, and each stub definition is treated as a single test. We assume that it contains at least one directory to be used as the test class name. If there is more than one level of nested directories, all except the last one is used as the package name. Consider the following structure:

src/test/resources/contracts/myservice/shouldCreateUser.groovy
src/test/resources/contracts/myservice/shouldReturnUser.groovy

给定该结构,Spring Cloud Contract Verifier 会创建一个名为 defaultBasePackage.MyService 的测试类,其中包含两个方法:

Given that structure, Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService with two methods:

  • shouldCreateUser()

  • shouldReturnUser()

Run Plugin

generateTests 插件目标指定为在称为 generate-test-sources 的阶段调用。如果您希望它成为您的构建过程的一部分,则无需执行任何操作。如果您只想生成测试,请调用 generateTests 目标。

The generateTests plugin goal is assigned to be invoked in the phase called generate-test-sources. If you want it to be part of your build process, you need not do anything. If you want only to generate tests, invoke the generateTests goal.

如果您希望从 Maven 运行存根,请调用使用存根作为 spring.cloud.contract.verifier.stubs 系统属性运行的 run 目标,如下所示:

If you want to run stubs from Maven, call the run goal with the stubs to run as the spring.cloud.contract.verifier.stubs system property as follows:

mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:run \-Dspring.cloud.contract.verifier.stubs="com.acme:service-name"

mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:run \ -Dspring.cloud.contract.verifier.stubs="com.acme:service-name"

Configure plugin

若要更改默认配置,您可以向插件定义或 execution 定义添加 configuration 部分,如下所示:

To change the default configuration, you can add a configuration section to the plugin definition or the execution definition, as follows:

<plugin>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>convert</goal>
                <goal>generateStubs</goal>
                <goal>generateTests</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
        <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
    </configuration>
</plugin>

Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, which is based on Spring’s MockMvc. You can also change it to WebTestClient, JaxRsClient, or Explicit (for real HTTP calls).

  • basePackageForTests: Specifies the base package for all generated tests. If not set, the value is picked from the package of baseClassForTests and from packageWithBaseClasses. If neither of these values are set, the value is set to org.springframework.cloud.contract.verifier.tests.

  • ruleClassForTests: Specifies a rule that should be added to the generated test classes.

  • baseClassForTests: Creates a base class for all generated tests. By default, if you use Spock classes, the class is spock.lang.Specification.

  • contractsDirectory: Specifies a directory that contains contracts written with the Groovyn DSL. The default directory is /src/test/resources/contracts.

  • generatedTestSourcesDir: Specifies the test source directory where tests generated from the Groovy DSL should be placed. By default, its value is $buildDir/generated-test-sources/contracts.

  • generatedTestResourcesDir: Specifies the test resource directory for resources used by the generated tests.

  • testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT), and JUnit 5 are supported, with JUnit 4 being the default framework.

  • packageWithBaseClasses: Defines a package where all the base classes reside. This setting takes precedence over baseClassForTests. The convention is such that, if you have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set the value of the packageWithBaseClasses property to com.example.base, Spring Cloud Contract Verifier assumes that there is a BarBazBase class under the com.example.base package. In other words, the system takes the last two parts of the package, if they exist, and forms a class with Base as a suffix.

  • baseClassMappings: Specifies a list of base class mappings that provide contractPackageRegex (which is checked against the package where the contract is located) and baseClassFQN( which maps to the fully qualified name of the base class for the matched contract). For example, if you have a contract under src/test/resources/contract/foo/bar/baz/ and map the .* → com.example.base.BaseClass property, the test class generated from these contracts extends com.example.base.BaseClass. This setting takes precedence over packageWithBaseClasses and baseClassForTests.

  • contractsProperties: A map that contains properties to be passed to Spring Cloud Contract components. Those properties might be used by (for example) built-in or custom Stub Downloaders.

  • failOnNoContracts: When enabled, will throw an exception when no contracts were found. Defaults to true.

  • failOnInProgress: If set to true, then, if any contracts that are in progress are found, they break the build. On the producer side, you need to be explicit about the fact that you have contracts in progress and take into consideration that you might be causing false positive test results on the consumer side. Defaults to true.

  • incrementalContractTests: When enabled, tests are created only when contracts have changed since last build. Defaults to true.

  • incrementalContractStubs: When enabled, stubs are created only when contracts have changed since last build. Defaults to true.

  • incrementalContractStubsJar: When enabled, stubs jar is created only when stubs have changed since last build. Defaults to true. *httpPort : HTTP port for the WireMock server that serves stubs. Currently spring.cloud.contract.verifier.http.port property works only when serving stubs from the directory. Otherwise, when providing stubs id, port have to be included in the id string. *skip: Set this to true to bypass the verifier execution. *skipTestOnly: Set this to true to bypass verifier test generation. *stubs : List of stubs to be downloaded and ran in a colon separated Ivy notation. *minPort : Specifies the minimal port at which the stub should start. *maxPort : Specifies the maximal port at which the stub should start. *waitForKeyPressed : Specifies if the plugin should wait for the user to press the key after starting the stubs. *stubsClassifier: Specifies the classifier used by stubs artifacts.

如果您希望从 Maven 仓库下载您的契约定义,您可以使用以下选项:

If you want to download your contract definitions from a Maven repository, you can use the following options:

  • contractDependency: The contract dependency that contains all the packaged contracts.

  • contractsPath: The path to the concrete contracts in the JAR with packaged contracts. Defaults to groupid/artifactid where gropuid is slash separated.

  • contractsMode: Picks the mode in which stubs are found and registered.

  • deleteStubsAfterTest: If set to false, do not remove any downloaded contracts from temporary directories.

  • contractsRepositoryUrl: URL to a repository with the artifacts that have contracts. If it is not provided, use the current Maven ones.

  • contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.

  • contractsRepositoryPassword: The password to be used to connect to the repo with contracts.

  • contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.

  • contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

我们仅缓存非快照、明确提供的版本(例如,+1.0.0.BUILD-SNAPSHOT 不会被缓存)。默认情况下,此功能被启用。

We cache only non-snapshot, explicitly provided versions (for example + or 1.0.0.BUILD-SNAPSHOT do not get cached). By default, this feature is turned on.

以下列表描述了您可以在插件中启用的试验性功能:

The following list describes experimental features that you can turn on in the plugin:

  • convertToYaml: Converts all DSLs to the declarative YAML format. This can be extremely useful when you use external libraries in your Groovy DSLs. By turning this feature on (by setting it to true), you need not add the library dependency on the consumer side.

  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

Single Base Class for All Tests

当在默认(MockMvc)中使用 Spring Cloud Contract Verifier 时,您需要为所有生成的验收测试创建一个基础规范。在此类中,您需要指向一个端点,该端点应该经过验证。以下示例显示如何执行此操作:

When using Spring Cloud Contract Verifier in the default (MockMvc), you need to create a base specification for all generated acceptance tests. In this class, you need to point to an endpoint, which should be verified. The following example shows how to do so:

package org.mycompany.tests

import org.mycompany.ExampleSpringController
import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
import spock.lang.Specification

class MvcSpec extends Specification {
  def setup() {
   RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
  }
}

如果需要,您还可以设置整个内容,如下面的示例所示:

If necessary, you can also setup the whole context, as the following example shows:

import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
public abstract class BaseTestClass {

	@Autowired
	WebApplicationContext context;

	@Before
	public void setup() {
		RestAssuredMockMvc.webAppContextSetup(this.context);
	}
}

如果您使用 EXPLICIT 模式,您可以使用基本类来初始化整个被测试应用,类似于您在常规集成测试中的做法。以下示例演示如何执行此操作:

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app, similar to what you might do in regular integration tests. The following example shows how to do so:

import io.restassured.RestAssured;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
public abstract class BaseTestClass {

	@LocalServerPort
	int port;

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

如果您使用 JAXRSCLIENT 模式,则此基本类还应该包含 受保护的 WebTarget webTarget 字段。目前,测试 JAX-RS API 的唯一方法是启动 Web 服务器。

If you use the JAXRSCLIENT mode, this base class should also contain a protected WebTarget webTarget field. Right now, the only way to test the JAX-RS API is to start a web server.

Using Different Base Classes for Contracts

如果您的基本类在契约之间有所不同,您可以告诉 Spring Cloud Contract 插件哪个类应该被自动生成的测试扩展。您有两种选择:

If your base classes differ between contracts, you can tell the Spring Cloud Contract plugin which class should get extended by the autogenerated tests. You have two options:

  • Follow a convention by providing a value for packageWithBaseClasses

  • Provide explicit mapping with baseClassMappings

By Convention

约定是这样的,如果您有契约(例如)在`src/test/resources/contract/foo/bar/baz/` 下,并且将 packageWithBaseClasses 属性的值设置为 com.example.base,那么 Spring Cloud ContractVerifier 假定在 com.example.base 包下有一个 BarBazBase 类。换句话说,系统采用包的最后两部分(如果存在),并通过 Base 后缀形成一个类。此规则优先于 baseClassForTests。以下示例演示了它在 contracts 闭包中的工作方式:

The convention is such that if you have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set the value of the packageWithBaseClasses property to com.example.base, then Spring Cloud Contract Verifier assumes that there is a BarBazBase class under the com.example.base package. In other words, the system takes the last two parts of the package, if they exist, and forms a class with a Base suffix. This rule takes precedence over baseClassForTests. The following example shows how it works in the contracts closure:

Unresolved directive in maven-project.adoc - include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-generated-baseclass/pom.xml[]

By Mapping

您可以手动将契约包的正则表达式映射到匹配契约的基础类的完全限定名。您必须提供一个名为 baseClassMappings 的列表,该列表由 baseClassMapping 对象组成,每个对象采用 contractPackageRegexbaseClassFQN 映射。考虑以下示例:

You can manually map a regular expression of the contract’s package to the fully qualified name of the base class for the matched contract. You have to provide a list called baseClassMappings that consists of baseClassMapping objects that each take a contractPackageRegex to baseClassFQN mapping. Consider the following example:

Unresolved directive in maven-project.adoc - include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-baseclass-from-mappings/pom.xml[]

假设您在这两个位置有契约:

Assume that you have contracts under these two locations:

  • src/test/resources/contract/com/

  • src/test/resources/contract/foo/

通过提供 baseClassForTests,我们可以在映射未成功的情况下的预备(您还可以提供 packageWithBaseClasses 作为预备)。这样,从 src/test/resources/contract/com/ 契约生成的测试会扩展 com.example.ComBase,而其余测试会扩展 com.example.FooBase

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. (You can also provide the packageWithBaseClasses as a fallback.) That way, the tests generated from src/test/resources/contract/com/ contracts extend the com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

Invoking Generated Tests

Spring Cloud Contract Maven 插件会在名为 /generated-test-sources/contractVerifier 的目录中生成验证代码,并将此目录附加到 testCompile 目标。

The Spring Cloud Contract Maven Plugin generates verification code in a directory called /generated-test-sources/contractVerifier and attaches this directory to testCompile goal.

对于 Groovy Spock 代码,您可以使用以下内容:

For Groovy Spock code, you can use the following:

<plugin>
	<groupId>org.codehaus.gmavenplus</groupId>
	<artifactId>gmavenplus-plugin</artifactId>
	<version>1.5</version>
	<executions>
		<execution>
			<goals>
				<goal>testCompile</goal>
			</goals>
		</execution>
	</executions>
	<configuration>
		<testSources>
			<testSource>
				<directory>${project.basedir}/src/test/groovy</directory>
				<includes>
					<include>**/*.groovy</include>
				</includes>
			</testSource>
			<testSource>
				<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
				<includes>
					<include>**/*.groovy</include>
				</includes>
			</testSource>
		</testSources>
	</configuration>
</plugin>

要确保提供者端符合定义的契约,您需要调用 mvn generateTest 测试。

To ensure that the provider side is compliant with defined contracts, you need to invoke mvn generateTest test.

Pushing Stubs to SCM

如果您使用 SCM(源代码管理)存储库来保留契约和存根,您可能需要将将存根推送到存储库的步骤自动化。为此,您可以添加 pushStubsToScm 目标。以下示例演示如何执行此操作:

If you use the SCM (Source Control Management) repository to keep the contracts and stubs, you might want to automate the step of pushing stubs to the repository. To do that, you can add the pushStubsToScm goal. The following example shows how to do so:

<plugin>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
    <version>${spring-cloud-contract.version}</version>
    <extensions>true</extensions>
    <configuration>
        <!-- Base class mappings etc. -->

        <!-- We want to pick contracts from a Git repository -->
        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>

        <!-- We reuse the contract dependency section to set up the path
        to the folder that contains the contract definitions. In our case the
        path will be /groupId/artifactId/version/contracts -->
        <contractDependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>${project.artifactId}</artifactId>
            <version>${project.version}</version>
        </contractDependency>

        <!-- The contracts mode can't be classpath -->
        <contractsMode>REMOTE</contractsMode>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <!-- By default we will not push the stubs back to SCM,
                you have to explicitly add it as a goal -->
                <goal>pushStubsToScm</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Using the SCM Stub Downloader中,您可以找到可以通过`<configuration><contractsProperties>`映射、系统属性或环境变量传递的所有可能的配置选项。例如,您可以指定一个具体的branch来签出,而不是默认branch。

Under Using the SCM Stub Downloader, you can find all possible configuration options that you can pass through the <configuration><contractsProperties> map, a system property, or an environment variable. For instance, you could specify a concrete branch to checkout, instead of the default one

<plugin>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
    <version>${spring-cloud-contract.version}</version>
    <extensions>true</extensions>
    <configuration>
        <!-- Base class mappings etc. -->

        <!-- We want to pick contracts from a Git repository -->
        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
	<contractsProperties>
            <git.branch>another_branch</git.branch>
        </contractsProperties>

        <!-- We reuse the contract dependency section to set up the path
        to the folder that contains the contract definitions. In our case the
        path will be /groupId/artifactId/version/contracts -->
        <contractDependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>${project.artifactId}</artifactId>
            <version>${project.version}</version>
        </contractDependency>

        <!-- The contracts mode can't be classpath -->
        <contractsMode>REMOTE</contractsMode>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <!-- By default we will not push the stubs back to SCM,
                you have to explicitly add it as a goal -->
                <goal>pushStubsToScm</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Maven Plugin and STS

下图显示了在使用 STS 时可能看到的异常:

The following image shows an exception that you may see when you use STS:

sts exception

当您单击错误标记时,您应该看到类似以下内容:

When you click on the error marker, you should see something like the following:

 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
 cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
 org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
...
 org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
 org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
 org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at

要解决此问题,请在 pom.xml 中提供以下部分:

To fix this issue, provide the following section in your pom.xml:

<build>
    <pluginManagement>
        <plugins>
            <!--This plugin's configuration is used to store Eclipse m2e settings
                only. It has no influence on the Maven build itself. -->
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                             <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.springframework.cloud</groupId>
                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
                                    <versionRange>[1.0,)</versionRange>
                                    <goals>
                                        <goal>convert</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <execute />
                                </action>
                             </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

Maven Plugin with Spock Tests

您可以选择 Spock Framework使用Maven和Gradle创建和运行自动生成的合同验证测试。然而,在使用Gradle时很简单,而在Maven中,您需要一些额外的设置才能使测试得到正确编译和执行。

You can select the Spock Framework for creating and running the auto-generated contract verification tests with both Maven and Gradle. However, while using Gradle is straightforward, in Maven, you need some additional setup in order to make the tests compile and execute properly.

首先,您必须使用一个插件,例如 GMavenPlus插件, 将Groovy添加到您的项目中。在GMavenPlus插件中,您需要明确设置测试源,包括base测试类被定义的路径以及生成合同测试被添加的路径。{samples_url}/producer_with_spock/pom.xml [以下示例]展示了如何做到这一点。

First of all, you must use a plugin, such as the GMavenPlus plugin, to add Groovy to your project. In GMavenPlus plugin, you need to explicitly set test sources, including both the path where your base test classes are defined and the path were the generated contract tests are added. The {samples_url}/producer_with_spock/pom.xml[following example] shows how to do so.

如果您支持以 `Spec`结尾的测试类命名约定,您还需要调整您的 Maven Surefire 插件设置,如 {samples_url}/producer_with_spock/pom.xml[以下示例]所示。

If you uphold the Spock convention of ending the test class names with Spec, you also need to adjust your Maven Surefire plugin setup, as the {samples_url}/producer_with_spock/pom.xml[following example] shows.