5

我尝试使用以下代码片段为 spring rest mocks 设置上下文路径:

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())));
}

但我收到以下错误:

java.lang.IllegalArgumentException: requestURI [/] does not start with contextPath [/api]

怎么了? 是否可以在代码中的单个位置指定 contextPath,例如直接在构建器中?

编辑

这里是控制器

@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);
    }
}
4

2 回答 2

16

您需要在传递给的路径中包含上下文路径get

在您在问题中显示的情况下,上下文路径是/api并且您想要发出请求,/因此您需要传递/api/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())));
}
于 2016-02-16T17:16:23.163 回答
4

许多人所做的只是在 mockMvc测试中不使用上下文路径。您只需指定@RequestMappingURI:

@Test
public void index() throws Exception {
    this.mockMvc.perform(get("/business-case/1234").accept(MediaTypes.HAL_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("_links.business-cases", is(notNullValue())));
}
于 2019-01-25T18:51:41.787 回答