使用公共代码重新启动java
所以我是一个初学者,请放心
在JAVA中,为了便于演示和使用,我缩短了代码。我有一个类,它有以下代码:
public class ApiEndpointHelper {
public static String postIdRequest(String requestBody) {
String jsonBody = FileReader.getFile(requestBody);
Response response = RestAssured.given()
.auth()
.basic("userbob", "bobspassword")
.contentType(ContentType.JSON)
.body(jsonBody)
.when()
.post("http://localhost:8080/report/v1/");
response
.then()
.log().ifError().and()
.statusCode(200);
return response.asString();
}
public static String getId() {
Response response = RestAssured.given()
.auth()
.basic("NEWuserjames", "jamesspassword")
.contentType(ContentType.JSON)
.when()
.get("http://localhost:3099/v1/");
response
.then()
.log().ifError().and()
.statusCode(200);
return response.asString();
}
}
然后是另一个课程:
public class BasicTest extends ApiEndpointHelper {
@Test
public void Query_endpoint() {
String ActualResponse = ApiEndpointHelper.getId();
assertJsonEquals(resource("responseExpected.json"),
ActualResponse, when(IGNORING_ARRAY_ORDER));
}
}
我的问题是:
我如何使用代码,以便在某个地方声明常见的主体项,如身份验证标题、内容类型、帖子URL等,然后所有请求都可以获取它们?此外,两者都使用相同的身份验证头,但密码不同。有什么聪明的方法能让它成功吗?! 请参见方法中的:“PostdRequest”和“getId”。我想我可以使用RequestSpecification,但不确定如何使用! 有人能举例说明吗,最好使用当前的上下文
# 1 楼答案
将通用代码提取到带有参数的方法中:
如果需要,可以传递用于身份验证的参数
类似地,您可以将URL构造提取到方法中。这都是基本的编程,所以除非你有一个特定的问题,否则这个问题对Stackoverflow来说可能太广泛了