加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Spring REST模拟上下文路径

发布时间:2020-12-15 04:32:27 所属栏目:Java 来源:网络整理
导读:我尝试使用以下代码片段为 spring rest mocks设置上下文路径: private MockMvc mockMvc;@Beforepublic void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .alw
我尝试使用以下代码片段为 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);
    }
}

解决方法

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

如果您已在问题中显示,则上下文路径为/ api,您希望向/请求/您需要传递/ api /来获取:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读