SpringCloud Stub Runner JUnit规则和Stub Runner JUnit5扩展

2023-12-11 17:12 更新

Stub Runner带有JUnit规则,因此您可以很容易地下载和运行给定组和工件ID的存根:

@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服务器提供有效的WireMock定义的所有JSON文件
  • 也可以发送消息(记住要通过MessageVerifier接口的实现)

Stub Runner使用Eclipse Aether机制下载Maven依赖项。查看他们的文档以获取更多信息。

由于StubRunnerRuleStubRunnerExtension实现了StubFinder,因此它们使您可以找到已启动的存根:

package org.springframework.cloud.contract.stubrunner;

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();

}

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测试中的用法示例:

	@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");
	}

	private String httpGet(String url) throws Exception {
		try (InputStream stream = URI.create(url).toURL().openStream()) {
			return StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
		}
	}

}

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 "";
	}
}

检查JUnit和SpringCommon属性,以获取有关如何应用Stub Runner全局配置的更多信息。

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

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号