RestAssured报错:待合并的Specification不能为空问题求助
问题原因
SetupRequestSpecBuilder方法用了static修饰,但@BeforeEach注解的方法必须是非静态实例方法,JUnit不会执行静态的@BeforeEach方法,导致reqSpec始终为null,调用given().spec(reqSpec)时就会抛出“Specification to merge with cannot be null”错误。- 你把
date_req参数写死在RequestSpec里,没法动态切换不同日期,违背了复用API获取不同日期数据的需求。
修复方案
移除方法的static修饰符
让JUnit能正确初始化reqSpec:@BeforeEach public void SetupRequestSpecBuilder() { // 去掉static修饰符 reqBuilder = new RequestSpecBuilder(); reqBuilder.setContentType("application/json"); reqBuilder.addHeader("Content-Type", "application/json"); reqBuilder.addQueryParam("ap_type", apptype); reqBuilder.addQueryParam("days", days); reqBuilder.addQueryParam("room_id", roomid); // 不要在这里固定date_req,留到请求时动态传入 reqSpec = reqBuilder.build(); }动态传入date_req参数
修改查询方法,支持传入任意日期,复用同一个RequestSpec:@Step("user perform a search for date: {0}") public void GETDairySearch(LocalDate targetDate) { logger.info("STEP: user perform a search for date: {}", targetDate); response = SerenityRest.given().spec(reqSpec) .queryParam("date_req", targetDate.toString()) // 动态添加日期参数 .when() .get(endpoint + basePath); response.then().log().all().assertThat().statusCode(200); logger.info(" Endpoint is: :: " + endpoint + basePath); template_slot_id = response.jsonPath().getString("diary.template_slot_id[0]"); template_slot_id_new = response.jsonPath().getString("diary.template_slot_id[1]"); logger.info(" Slot_id_for_Date {} :: {}", targetDate, template_slot_id); logger.info("STEP: user completed GET diary search"); }调用示例
在测试用例中传入不同日期即可实现多场景复用:@Test void testCurrentDay() { GETDairySearch(LocalDate.now()); } @Test void testNextDay() { GETDairySearch(LocalDate.now().plusDays(1)); }
内容的提问来源于stack exchange,提问作者fareen taj
相关产品推荐
相关产品推荐

