使用 Stub Runner Boot 应用

Spring Cloud Contract Stub Runner Boot 是一个 Spring Boot 应用,它暴露 REST 端点来触发消息标签并访问 WireMock 服务器。

Stub Runner Boot 安全

Stub Runner Boot 应用设计上是不安全的 - 保护它需要为所有 Stub 添加安全性,即使它们实际上不需要。因为这是一个测试工具 - 服务器**不打算**用于生产环境。

预期**只有受信任的客户端**才能访问 Stub Runner Boot 服务器。您不应该在不受信任的位置将此应用作为 Fat Jar 或 Docker 镜像 运行。

Stub Runner 服务器

要使用 Stub Runner 服务器,请添加以下依赖

compile "org.springframework.cloud:spring-cloud-starter-stub-runner"

然后用 @EnableStubRunnerServer 注解一个类,构建一个 fat jar,它就可以工作了。

有关属性,请参阅Stub Runner Spring 部分。

Stub Runner Server Fat Jar

您可以从 Maven 下载独立的 JAR(例如,版本 2.0.1.RELEASE),方法是运行以下命令

$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...

Spring Cloud CLI

Spring Cloud CLI 项目的 1.4.0.RELEASE 版本开始,您可以通过运行 spring cloud stubrunner 来启动 Stub Runner Boot。

要传递配置,您可以在当前工作目录、名为 config 的子目录或 ~/.spring-cloud 中创建 stubrunner.yml 文件。该文件可以类似于以下运行本地安装的 stub 的示例

示例 1. stubrunner.yml
stubrunner:
  stubsMode: LOCAL
  ids:
    - com.example:beer-api-producer:+:9876

然后您可以从终端窗口调用 spring cloud stubrunner 来启动 Stub Runner 服务器。它在端口 8750 上可用。

端点

Stub Runner Boot 提供两个端点

HTTP

对于 HTTP,Stub Runner Boot 提供以下端点

  • GET /stubs: 返回所有运行中的 stub 的列表,使用 ivy:integer 格式

  • GET /stubs/{ivy}: 返回给定 ivy 格式的端口(调用此端点时,ivy 也可以仅为 artifactId

消息

对于消息传递,Stub Runner Boot 提供以下端点

  • GET /triggers: 返回所有运行中的 label 的列表,使用 ivy : [ label1, label2 …​] 格式

  • POST /triggers/{label}: 运行带有 label 的触发器

  • POST /triggers/{ivy}/{label}: 运行给定 ivy 格式的带有 label 的触发器(调用此端点时,ivy 也可以仅为 artifactId

示例

以下示例展示了 Stub Runner Boot 的典型用法

@SpringBootTest(classes = StubRunnerBoot, properties = "spring.cloud.zookeeper.enabled=false")
@ActiveProfiles("test")
class StubRunnerBootSpec {

	@Autowired
	StubRunning stubRunning

	@BeforeEach
	void setup() {
		RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning),
				new TriggerController(stubRunning))
	}

	@Test
	void 'should return a list of running stub servers in "full ivy port" notation'() {
		when:
			String response = RestAssuredMockMvc.get('/stubs').body.asString()
		then:
			def root = new JsonSlurper().parseText(response)
			assert root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs' instanceof Integer
	}

	@Test
	void 'should return a port on which a #stubId stub is running'() {
		given:
		def stubIds = ['org.springframework.cloud.contract.verifier.stubs:bootService:+:stubs',
				   'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs',
				   'org.springframework.cloud.contract.verifier.stubs:bootService:+',
				   'org.springframework.cloud.contract.verifier.stubs:bootService',
				   'bootService']
		stubIds.each {
			when:
				def response = RestAssuredMockMvc.get("/stubs/${it}")
			then:
				assert response.statusCode == 200
				assert Integer.valueOf(response.body.asString()) > 0
		}
	}

	@Test
	void 'should return 404 when missing stub was called'() {
		when:
			def response = RestAssuredMockMvc.get("/stubs/a:b:c:d")
		then:
			assert response.statusCode == 404
	}

	@Test
	void 'should return a list of messaging labels that can be triggered when version and classifier are passed'() {
		when:
			String response = RestAssuredMockMvc.get('/triggers').body.asString()
		then:
			def root = new JsonSlurper().parseText(response)
			assert root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["return_book_1"])
	}

	@Test
	void 'should trigger a messaging label'() {
		given:
			StubRunning stubRunning = Mockito.mock(StubRunning)
			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
		when:
			def response = RestAssuredMockMvc.post("/triggers/delete_book")
		then:
			response.statusCode == 200
		and:
			Mockito.verify(stubRunning).trigger('delete_book')
	}

	@Test
	void 'should trigger a messaging label for a stub with #stubId ivy notation'() {
		given:
			StubRunning stubRunning = Mockito.mock(StubRunning)
			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
		and:
			def stubIds = ['org.springframework.cloud.contract.verifier.stubs:bootService:stubs', 'org.springframework.cloud.contract.verifier.stubs:bootService', 'bootService']
		stubIds.each {
			when:
				def response = RestAssuredMockMvc.post("/triggers/$it/delete_book")
			then:
				assert response.statusCode == 200
			and:
				Mockito.verify(stubRunning).trigger(it, 'delete_book')
		}

	}

	@Test
	void 'should throw exception when trigger is missing'() {
		when:
		BDDAssertions.thenThrownBy(() -> RestAssuredMockMvc.post("/triggers/missing_label"))
		.hasMessageContaining("Exception occurred while trying to return [missing_label] label.")
		.hasMessageContaining("Available labels are")
		.hasMessageContaining("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs=[]")
		.hasMessageContaining("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=")
	}

}

结合服务发现使用 Stub Runner Boot

使用 Stub Runner Boot 的一种方式是将其用作“冒烟测试”的 stub 源。这意味着什么?假设您不想在测试环境中部署 50 个微服务以查看您的应用是否正常工作。您已经在构建过程中运行了一系列测试,但您还想确保您的应用打包正常。您可以将您的应用部署到环境中,启动它,并在其上运行少量测试以查看其是否工作。我们可以将这些测试称为“冒烟测试”,因为它们的目的只是检查少数测试场景。

这种方法的问题在于,如果您使用微服务,您很可能也使用服务发现工具。Stub Runner Boot 让您可以通过启动所需的 stub 并将其注册到服务发现工具中来解决此问题。

现在假设我们想启动此应用以便自动注册 stub。我们可以通过使用 java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar 来运行应用,其中 ${SYSTEM_PROPS}

这样,您部署的应用就可以通过服务发现向已启动的 WireMock 服务器发送请求。最有可能的是,第 1 到 3 点可以在 application.yml 中默认设置,因为它们不太可能更改。这样,无论何时启动 Stub Runner Boot,您都可以只提供要下载的 stub 列表。