问题描述
我需要使用协议测试和REST保证检查类型为/ meeting / id的api。 ID可能会更改,我想在测试之前创建一个项目,然后注入其ID以覆盖合同url路径中设置的内容,但不确定如何执行此操作?
这是我的消费者:
@ExtendWith(PactConsumerTestExt.class)
public class PactConsumerTest {
Map<String,String> headers = new HashMap<>();
String storeMeetingPath = "/meeting/256";
@Pact(provider = VC,consumer = ED_UI)
public RequestResponsePact createPact(PactDslWithProvider builder) {
headers.put("Content-Type","application/json");
headers.put("Accept","application/json");
return builder
.given("A request to retrieve a meeting for a user")
.uponReceiving("A request to retrieve a meeting for a user")
.path(storeMeetingPath)
.method("GET")
.headers(headers)
.willRespondWith()
.body(new PactDslJsonBody()
.integerType("meetingId",3)
.stringType("meetingTitle","My title")
.stringType("meetingDescription","My description"))
.status(200)
.toPact();
}
@Test
@PactTestFor(providerName = VC,port = "8080")
public void runtest() {
//Mock url
RestAssured.baseURI = "http://localhost:8080";
RequestSpecification rq = RestAssured
.given()
.headers(headers)
.when();
rq.get(storeMeetingPath);
}
}
这里是我的提供者:
@Provider(VC)
@PactFolder("target/pacts")
public class PactProviderTest {
@TestTemplate
@ExtendWith(PactVerificationInvocationContextProvider.class)
void pactTestTemplate(PactVerificationContext context,HttpRequest request) {
request.addHeader("Authorization",AUTHORIZATION_TOKEN);
context.verifyInteraction();
}
@BeforeEach
void before(PactVerificationContext context) {
context.setTarget(new HttpsTestTarget(getBasePactEndpoint(),443,"/"));
// Will create a meeting and retrieve the id from here but how to use this to overwrite what is there on the consumer?
getAuthorizationToken(UserType.TEACHER);
}
@State("A request to retrieve a meeting for a user")
public void sampleState() {
}
}
非常感谢您。
解决方法
了解了有关此问题的答案,以防对其他人有帮助:
替换此行
.path(storeMeetingPath)
使用
.pathFromProviderState("/meeting/${id}","/meeting/500")
这样我们就有一个带有默认值的模板。
然后改变
@State("A request to retrieve a meeting for a user")
public void sampleState() {
}
要具有此属性,以便它返回一个映射,该映射将设置要注入的元素的键和值。
@State("A request to retrieve a meeting for a user")
public Map sampleState() {
Map<String,Integer> map = new HashMap<>();
map.put("id",391);
return map;
}
辅助文档:
提供者:https://github.com/DiUS/pact-jvm/tree/master/provider/junit#returning-values-that-can-be-injected