下面的代码适合我:
@Test (priority=1, dependsOnMethods = {"checkIfAllServicesAreUp"})
public void verifyCreateUser() {
RestAssured.baseURI = "someValidURI";
RestAssured.basePath = "userservice/user/";
RequestSpecification spec = new RequestSpecBuilder().setContentType(ContentType.JSON).log(LogDetail.METHOD).build();
response = RestAssured.given().spec(spec).headers("source","APP").body("{ }").when().post("");
}
但是当我以下面的方式将RequestSpecification
相关代码移动到@BeforeClass
下时:
private RequestSpecification spec;
@BeforeClass
public void setSpec() {
spec = new RequestSpecBuilder().setContentType(ContentType.JSON).log(LogDetail.METHOD).build();
}
@Test (priority=1, dependsOnMethods = {"checkIfAllServicesAreUp"})
public void verifyCreateUser() {
RestAssured.baseURI = "someValidURI";
RestAssured.basePath = "userservice/user/";
response = RestAssured.given().spec(spec).headers("source","APP").body("{ }").when().post("");
}
我的 API 测试返回错误代码 405(方法不允许)。
似乎 spec
正在覆盖我的测试方法 verifyCreateUser
中的 RestAssured.basePath
赋值,因为我没有在 中设置相同的内容>spec
显式,并且 POST 调用在 someValidURI
而不是 someValidURI+/userservice/user
处被命中,因此出现 405 错误代码。我不想在 spec
中设置 basePath
,因为它对于我的每个测试方法都是不同的。请在这里帮助找到一个优雅的解决方案。
最佳答案
如下所述修改了我的代码,现在它工作正常:
@Test (priority=1, dependsOnMethods = {"checkIfAllServicesAreUp"})
public void verifyCreateUser() {
RestAssured.baseURI = "someValidURI";
RequestSpecification spec = new RequestSpecBuilder().setBasePath("userservice/user/").setContentType(ContentType.JSON).log(LogDetail.METHOD).build();
response = RestAssured.given().spec(spec).headers("source","APP").body("{ }").when().post("");
}
显然,我之前为每个测试配置 basePath
的方式不正确。我现在在 spec
内完成。
希望这对以后的人有帮助。
关于java - 将 RequestSpecification 代码移到 @BeforeClass 下后出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43468564/