https://stackoverflow.com/a/48859553/309683 中提到的属性名称(即)不正确,至少自春季云合同版本以来是这样。wiremock.port
2.1.2.RELEASE
1. 工作实例
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
@AutoConfigureWireMock(port = 0)
public class PortServiceTest {
@Autowired
private Environment environment;
@Test
public void shouldPopulateEnvironmentWithWiremockPort() {
assertThat(environment.containsProperty("wiremock.server.port")).isTrue();
assertThat(environment.getProperty("wiremock.server.port")).matches("\\d+");
}
}
2. 其他 WireMock 特性
除 之外,还会使用一些其他属性填充环境:wiremock.server.port
@AutoConfigureWireMock
wiremock.server.https-port
wiremock.server.stubs[]
wiremock.server.files[]
3. Gradle 依赖关系
要在基于Gradle的项目中使用Spring Cloud Contract WireMock,请将以下依赖项添加到项目中:
testImplementation 'org.springframework.cloud:spring-cloud-contract-wiremock:${version}'
4. 在文件中使用application.yaml
如果像这样配置测试文件:application.yaml
sample:
port: ${wiremock.server.port}
并定义以下豆类:
@Component
@ConfigurationProperties(prefix = "sample")
@Data
public class PortProperties {
private Integer port;
}
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PortService {
private final PortProperties config;
public Integer getPort() {
return config.getPort();
}
}
您可以验证 是否设置为随机选择的 wiremock 端口:sample.port
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
@AutoConfigureWireMock(port = 0)
public class PortServiceTest {
@Autowired
private Environment environment;
@Autowired
private PortService portService;
@Test
public void shouldReturnWireMockPort() {
assertThat(portService.getPort())
.isNotNull()
.isEqualTo(Integer.parseInt(environment.getProperty("wiremock.server.port")));
}
}