Stub Runner JUnit Rule 和 Stub Runner JUnit5 Extension

Stub Runner 附带了一个 JUnit 规则,可让您下载并运行给定 group ID 和 artifact ID 的 Stub,示例如下

@ClassRule
public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
	.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
	.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
	.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");

@BeforeClass
@AfterClass
public static void setupProps() {
	System.clearProperty("stubrunner.repository.root");
	System.clearProperty("stubrunner.classifier");
}

JUnit 5 也提供了 StubRunnerExtensionStubRunnerRuleStubRunnerExtension 的工作方式非常相似。调用规则或扩展后,Stub Runner 会连接到您的 Maven 仓库,并针对给定的依赖项列表尝试执行以下操作:

  • 下载它们

  • 在本地缓存它们

  • 将它们解压到临时文件夹

  • 为每个 Maven 依赖项启动一个 WireMock 服务器,端口可以是提供的范围内的随机端口或指定的端口

  • 将所有有效的 WireMock 定义 JSON 文件加载到 WireMock 服务器中

  • 发送消息(请记住传入 MessageVerifierSender 接口的实现)

Stub Runner 使用 Eclipse Aether 机制下载 Maven 依赖项。有关更多信息,请查阅他们的文档

由于 StubRunnerRuleStubRunnerExtension 实现了 StubFinder 接口,它们允许您查找已启动的 Stub,示例如下

import java.net.URL;
import java.util.Collection;
import java.util.Map;

import org.springframework.cloud.contract.spec.Contract;

/**
 * Contract for finding registered stubs.
 *
 * @author Marcin Grzejszczak
 */
public interface StubFinder extends StubTrigger {

	/**
	 * For the given groupId and artifactId tries to find the matching URL of the running
	 * stub.
	 * @param groupId - might be null. In that case a search only via artifactId takes
	 * place
	 * @param artifactId - artifact id of the stub
	 * @return URL of a running stub or throws exception if not found
	 * @throws StubNotFoundException in case of not finding a stub
	 */
	URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException;

	/**
	 * For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]}
	 * tries to find the matching URL of the running stub. You can also pass only
	 * {@code artifactId}.
	 * @param ivyNotation - Ivy representation of the Maven artifact
	 * @return URL of a running stub or throws exception if not found
	 * @throws StubNotFoundException in case of not finding a stub
	 */
	URL findStubUrl(String ivyNotation) throws StubNotFoundException;

	/**
	 * @return all running stubs
	 */
	RunningStubs findAllRunningStubs();

	/**
	 * @return the list of Contracts
	 */
	Map<StubConfiguration, Collection<Contract>> getContracts();

}

以下示例提供了有关使用 Stub Runner 的更多详细信息

Spock
@ClassRule
@Shared
StubRunnerRule rule = new StubRunnerRule()
		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
		.repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
		.withMappingsOutputFolder("target/outputmappingsforrule")


def 'should start WireMock servers'() {
	expect: 'WireMocks are running'
		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
		rule.findStubUrl('loanIssuance') != null
		rule.findStubUrl('loanIssuance') == rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
	and:
		rule.findAllRunningStubs().isPresent('loanIssuance')
		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
	and: 'Stubs were registered'
		"${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
		"${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
}

def 'should output mappings to output folder'() {
	when:
		def url = rule.findStubUrl('fraudDetectionServer')
	then:
		new File("target/outputmappingsforrule", "fraudDetectionServer_${url.port}").exists()
}
JUnit 4
@Test
public void should_start_wiremock_servers() throws Exception {
	// expect: 'WireMocks are running'
	then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")).isNotNull();
	then(rule.findStubUrl("loanIssuance")).isNotNull();
	then(rule.findStubUrl("loanIssuance"))
		.isEqualTo(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
	then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isNotNull();
	// and:
	then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
	then(rule.findAllRunningStubs()
		.isPresent("org.springframework.cloud.contract.verifier.stubs", "fraudDetectionServer")).isTrue();
	then(rule.findAllRunningStubs()
		.isPresent("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")).isTrue();
	// and: 'Stubs were registered'
	then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name")).isEqualTo("loanIssuance");
	then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name")).isEqualTo("fraudDetectionServer");
}
JUnit 5
// Visible for Junit
@RegisterExtension
static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension().repoRoot(repoRoot())
	.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
	.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
	.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
	.withMappingsOutputFolder("target/outputmappingsforrule");

@BeforeAll
@AfterAll
static void setupProps() {
	System.clearProperty("stubrunner.repository.root");
	System.clearProperty("stubrunner.classifier");
}

private static String repoRoot() {
	try {
		return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/").toURI().toString();
	}
	catch (Exception e) {
		return "";
	}
}

有关如何应用 Stub Runner 全局配置的更多信息,请参阅JUnit 和 Spring 的通用属性

要将 JUnit 规则或 JUnit 5 扩展与消息传递一起使用,您必须向规则构建器提供 MessageVerifierSenderMessageVerifierReceiver 接口的实现(例如,rule.messageVerifierSender(new MyMessageVerifierSender()))。如果您不这样做,那么每当您尝试发送消息时,都会抛出异常。

Maven 设置

Stub 下载器遵循 Maven 设置中关于本地仓库文件夹的配置。目前,仓库和 profile 的认证详细信息尚未考虑在内,因此您需要使用上面提到的属性来指定它们。

提供固定端口

您也可以在固定端口上运行 Stub。有两种不同的方式:一种是在属性中传递,另一种是使用 JUnit 规则的 Fluent API。

Fluent API

使用 StubRunnerRuleStubRunnerExtension 时,您可以添加要下载的 Stub,然后为最后下载的 Stub 指定端口。示例如下

@ClassRule
public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
	.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
	.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
	.withPort(35465)
	.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:35466");

@BeforeClass
@AfterClass
public static void setupProps() {
	System.clearProperty("stubrunner.repository.root");
	System.clearProperty("stubrunner.classifier");
}

对于前面的示例,以下测试是有效的

then(rule.findStubUrl("loanIssuance")).isEqualTo(URI.create("http://localhost:35465").toURL());
then(rule.findStubUrl("fraudDetectionServer")).isEqualTo(URI.create("http://localhost:35466").toURL());

Spring 集成 Stub Runner

Spring 集成 Stub Runner 会设置 Stub Runner 项目的 Spring 配置。

通过在配置文件中提供 Stub 列表,Stub Runner 会自动下载选定的 Stub 并在 WireMock 中注册它们。

如果您想查找 Stub 化依赖项的 URL,可以自动注入 StubFinder 接口并使用其方法,如下所示

@SpringBootTest(classes = Config, properties = [" stubrunner.cloud.enabled=false",
		'foo=${stubrunner.runningstubs.fraudDetectionServer.port}',
		'fooWithGroup=${stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port}'])
@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
		httpServerStubConfigurer = HttpsForFraudDetection)
@ActiveProfiles("test")
class StubRunnerConfigurationSpec {

	@Autowired
	StubFinder stubFinder
	@Autowired
	Environment environment
	@StubRunnerPort("fraudDetectionServer")
	int fraudDetectionServerPort
	@StubRunnerPort("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
	int fraudDetectionServerPortWithGroupId
	@Value('${foo}')
	Integer foo

	@BeforeAll
	static void setupSpec() {
		System.clearProperty("stubrunner.repository.root")
		System.clearProperty("stubrunner.classifier")
		WireMockHttpServerStubAccessor.clear()
	}

	@AfterAll
	static void cleanupSpec() {
		setupSpec()
	}

	@Test
	void 'should mark all ports as random'() {
		expect:
		WireMockHttpServerStubAccessor.everyPortRandom()
	}

	@Test
	void 'should start WireMock servers'() {
		expect: 'WireMocks are running'
		assert stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
		assert stubFinder.findStubUrl('loanIssuance') != null
		assert stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
		assert stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance')
		assert stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs')
		assert stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
		and:
		assert stubFinder.findAllRunningStubs().isPresent('loanIssuance')
		assert stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
		assert stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
		and: 'Stubs were registered'
		assert "${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
		assert "${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
		and: 'Fraud Detection is an HTTPS endpoint'
		assert stubFinder.findStubUrl('fraudDetectionServer').toString().startsWith("https")
	}

	@Test
	void 'should throw an exception when stub is not found'() {
		when:
			BDDAssertions.thenThrownBy(() -> stubFinder.findStubUrl('nonExistingService')).isInstanceOf(StubNotFoundException)
		when:
			BDDAssertions.thenThrownBy(() -> stubFinder.findStubUrl('nonExistingGroupId', 'nonExistingArtifactId'))
		.isInstanceOf(StubNotFoundException)
	}

	@Test
	void 'should register started servers as environment variables'() {
		expect:
		assert environment.getProperty("stubrunner.runningstubs.loanIssuance.port") != null
		assert stubFinder.findAllRunningStubs().getPort("loanIssuance") == (environment.getProperty("stubrunner.runningstubs.loanIssuance.port") as Integer)
		and:
		assert environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
		assert stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") as Integer)
		and:
		assert environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
		assert stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port") as Integer)
	}

	@Test
	void 'should be able to interpolate a running stub in the passed test property'() {
		given:
		int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
		expect:
		assert fraudPort > 0
		assert environment.getProperty("foo", Integer) == fraudPort
		assert environment.getProperty("fooWithGroup", Integer) == fraudPort
		assert foo == fraudPort
	}

//	@Issue("#573")
	@Test
	void 'should be able to retrieve the port of a running stub via an annotation'() {
		given:
		int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
		expect:
		assert fraudPort > 0
		assert fraudDetectionServerPort == fraudPort
		assert fraudDetectionServerPortWithGroupId == fraudPort
	}

	@Test
	void 'should dump all mappings to a file'() {
		when:
		def url = stubFinder.findStubUrl("fraudDetectionServer")
		then:
		assert new File("target/outputmappings/", "fraudDetectionServer_${url.port}").exists()
	}

	@Configuration
	@EnableAutoConfiguration
	static class Config {}

	@CompileStatic
	static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {

		private static final Log log = LogFactory.getLog(HttpsForFraudDetection)

		@Override
		WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
			if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
				int httpsPort = TestSocketUtils.findAvailableTcpPort()
				log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
				return httpStubConfiguration
						.httpsPort(httpsPort)
			}
			return httpStubConfiguration
		}
	}
}

这样做依赖于以下配置文件

stubrunner:
  repositoryRoot: classpath:m2repo/repository/
  ids:
    - org.springframework.cloud.contract.verifier.stubs:loanIssuance
    - org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer
    - org.springframework.cloud.contract.verifier.stubs:bootService
  stubs-mode: remote

除了使用属性文件外,您还可以使用 @AutoConfigureStubRunner 注解内的属性。以下示例通过在注解上设置值来达到相同的效果

@AutoConfigureStubRunner(ids = ["org.springframework.cloud.contract.verifier.stubs:loanIssuance",
 "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer",
 "org.springframework.cloud.contract.verifier.stubs:bootService"] ,
stubsMode = StubRunnerProperties.StubsMode.REMOTE ,
repositoryRoot = "classpath:m2repo/repository/" )

Stub Runner Spring 会为每个注册的 WireMock 服务器按以下方式注册环境变量。以下示例显示了 com.example:thing1com.example:thing2 的 Stub Runner ID

  • stubrunner.runningstubs.thing1.port

  • stubrunner.runningstubs.com.example.thing1.port

  • stubrunner.runningstubs.thing2.port

  • stubrunner.runningstubs.com.example.thing2.port

您可以在代码中引用这些值。

您还可以使用 @StubRunnerPort 注解注入正在运行的 Stub 的端口。注解的值可以是 groupid:artifactid 或仅是 artifactid。以下示例展示了 com.example:thing1com.example:thing2 的 Stub Runner ID。

@StubRunnerPort("thing1")
int thing1Port;
@StubRunnerPort("com.example:thing2")
int thing2Port;