junit 用于测试API的Mock @RequestAttribute

r7xajy2e  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(165)

//我拥有具有@请求属性(REQUEST_ATTRIBUTE_USER)User用户的控制器
//如何模拟@RequestAttribute以使测试正常工作

@GetMapping(value = "{shopAccountId}/delivery-days")
public String getDeliveryDates(

        @RequestAttribute(REQUEST_ATTRIBUTE_USER) User user,

        @ApiParam(value = "Shop Account Id", required = true) @PathVariable("shopAccountId") String shopAccountId,
        @ApiParam(value = "Internal", required = true) @RequestParam("internal") Boolean internal,
        @ApiParam(value = "Shipping Condition (0 = GROUND, 2 = DELIVERY_WILL_CALL, 3 = WILL_CALL)", required = true) @RequestParam("shipping_condition") String shippingCondition
) {
    return "123456";
}

public static final String SHOP_ACCOUNT_ID = "278ce8f2-f79f-438e-83f9-eae01ca0f802";

@Test
public void testGetDeliveryDays() {
    Response response = RestAssured
            .given()
            .queryParam("internal", Boolean.TRUE)
            .queryParam("shipping_condition", "0")
            .basePath(String.format("/accounts/%s/delivery-days", SHOP_ACCOUNT_ID))
            .get();
    assertEquals(200, response.getStatusCode(), "Expected status code 200.");
}
pepwfjgg

pepwfjgg1#

如果您使用Spring测试套件来测试您的控制器,这是非常容易的。模拟请求构建器有requestAtt方法,所以在测试中您可以

@Autowired
     private MockMvc mvc;

     //somewhere in the test code 
     mvc.perform(get("/some/path")
        .accept(MediaType.APPLICATION_JSON_VALUE)
        .requestAttr("user", new User())) //create user somehow

如果你想进行E2E测试(因为这就是rest assure的用途),你必须有一个请求拦截器,它(以某种方式)基于请求创建你的User对象,并将其作为requestAttribute附加到它处理的请求上。

相关问题