Java – spring rest simulation context path
•
Java
I tried to set the context path for spring rest mocks using the following code snippet:
private mockmvc mockmvc;
@Before
public void setUp() {
this.mockmvc = mockmvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.alwaysDo(document("{method-name}/{step}/",preprocessRequest(prettyPrint()),preprocessResponse(prettyPrint())))
.build();
}
@Test
public void index() throws Exception {
this.mockmvc.perform(get("/").contextPath("/api").accept(MediaTypes.HAL_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("_links.business-cases",is(notNullValue())));
}
But I received the following error:
java.lang.IllegalArgumentException: requestURI [/] does not start with contextPath [/api]
What's up? Can you specify a contextpath in a single location in your code, such as directly in the builder?
edit
Here is the controller
@RestController
@RequestMapping(value = "/business-case",produces = MediaType.APPLICATION_JSON_VALUE)
public class BusinessCaseController {
private static final Logger LOG = LoggerFactory.getLogger(BusinessCaseController.class);
private final BusinessCaseService businessCaseService;
@Autowired
public BusinessCaseController(BusinessCaseService businessCaseService) {
this.businessCaseService = businessCaseService;
}
@Transactional(rollbackFor = Throwable.class,readOnly = true)
@RequestMapping(value = "/{businessCaseId}",method = RequestMethod.GET)
public BusinessCaseDTO getBusinessCase(@PathVariable("businessCaseId") Integer businessCaseId) {
LOG.info("GET business-case for " + businessCaseId);
return businessCaseService.findOne(businessCaseId);
}
}
Solution
You need to include the context path in the path to be passed
If you have shown in the question, the context path is / API, and you want to / request / you need to pass / API / to get:
@Test
public void index() throws Exception {
this.mockmvc.perform(get("/api/").contextPath("/api").accept(MediaTypes.HAL_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("_links.business-cases",is(notNullValue())));
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
