Issue
// I have controller with @RequestAttribute(REQUEST_ATTRIBUTE_USER) User user
// How to mock @RequestAttribute to make test working
@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.");
}
Solution
It is very easy if you use Spring test suite do test your controller. Mock request builder has requestAtt
method, so in test you do
@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
If you want E2E testing (since that is what rest assure is for) you have to have eg request interceptor that creates (somehow) your User
object based on the request and attaches it as an requestAttribute
to the request it processes.
Answered By - Antoniossss
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)