存根跑者JUnit规则和存根跑者JUnit5扩展
Stub Runner 带有一个 JUnit 规则,允许你下载并运行给定的 stub 组和工件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("spring.cloud.contract.stubrunner.repository.root");
System.clearProperty("spring.cloud.contract.stubrunner.classifier");
}
一个StubRunner扩展也适用于JUnit 5。StubRunner规则和StubRunner扩展工作方式非常相似。规则或扩展之后为
调用 Stub Runner 连接到你的 Maven 仓库,并且对于给定的列表
依赖关系,尝试:
-
下载它们
-
将它们缓存到本地
-
解压到临时文件夹
-
为每个Maven依赖建立一个随机端口的WireMock服务器 端口范围或提供的端口
-
将所有有效的 WireMock 定义的 JSON 文件输入 WireMock 服务器
-
发送消息(记得传递一个实现
消息验证发送器接口)
Stub Runner 使用 Eclipse Aether 机制来下载 Maven 的依赖。 查看他们的文档以获取更多信息。
自从......StubRunner规则和StubRunner扩展实现StubFinder,他们让
你可以找到起始存根,如下示例所示:
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的细节:
@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()
}
@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");
}
// 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("spring.cloud.contract.stubrunner.repository.root");
System.clearProperty("spring.cloud.contract.stubrunner.classifier");
}
private static String repoRoot() {
try {
return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/").toURI().toString();
}
catch (Exception e) {
return "";
}
}
更多信息请参见JUnit和Spring的通用属性 如何应用存根运行器的全局配置。
要将 JUnit 规则或 JUnit 5 扩展与消息一起使用,你必须提供消息验证发送器和消息验证器接收器与规则构建器的接口(例如,rule.messageVerifierSender(new MyMessageVerifierSender())).
如果你不这样做,那么每当你尝试发送消息时,都会抛出异常。 |
Fluent API
当使用StubRunner规则或StubRunner扩展,你可以添加一个小作品来下载
然后通过端口传递最后一个下载的存根。以下示例展示了如何实现:
@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("spring.cloud.contract.stubrunner.repository.root");
System.clearProperty("spring.cloud.contract.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的短管跑者
带Spring的存根跑器设置了存根跑器项目的Spring配置。
通过在配置文件中提供存根列表,存根运行者会自动下载 并在 WireMock 中注册所选存根。
如果你想找到你 stubed 依赖的 URL,可以自动接线StubFinder界面与使用
其方法如下:
@SpringBootTest(classes = Config, properties = [" stubrunner.cloud.enabled=false",
'foo=${spring.cloud.contract.stubrunner.runningstubs.fraudDetectionServer.port}',
'fooWithGroup=${spring.cloud.contract.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("spring.cloud.contract.stubrunner.repository.root")
System.clearProperty("spring.cloud.contract.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("spring.cloud.contract.stubrunner.runningstubs.loanIssuance.port") != null
assert stubFinder.findAllRunningStubs().getPort("loanIssuance") == (environment.getProperty("spring.cloud.contract.stubrunner.runningstubs.loanIssuance.port") as Integer)
and:
assert environment.getProperty("spring.cloud.contract.stubrunner.runningstubs.fraudDetectionServer.port") != null
assert stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("spring.cloud.contract.stubrunner.runningstubs.fraudDetectionServer.port") as Integer)
and:
assert environment.getProperty("spring.cloud.contract.stubrunner.runningstubs.fraudDetectionServer.port") != null
assert stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("spring.cloud.contract.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
}
}
}
具体作取决于以下配置文件:
spring.cloud.contract.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服务器。以下示例展示了 的 Stub Runner IDcom.example:thing1和com.example:thing2:
-
spring.cloud.contract.stubrunner.runningstubs.thing1.port -
spring.cloud.contract.stubrunner.runningstubs.com.example.thing1.port -
Spring.cloud.contract.stubrunner.runningstubs.thing2.port -
spring.cloud.contract.stubrunner.runningstubs.com.example.thing2.port
你可以在代码中引用这些值。
你也可以使用@StubRunnerPort注释以注入运行存根端口。
注释的值可以是Groupid:Artifactid或者仅仅是文物.
以下示例作品展示了 的 Stub Runner IDcom.example:thing1和com.example:thing2.
@StubRunnerPort("thing1")
int thing1Port;
@StubRunnerPort("com.example:thing2")
int thing2Port;