【问题标题】:Spring REST mock context pathSpring REST 模拟上下文路径
【发布时间】:2016-02-16 14:50:38
【问题描述】:

我尝试使用以下代码 sn-p 为 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);
    }
}

【问题讨论】:

  • 尝试发布你的控制器
  • 查看编辑。为什么投反对票?请记住,server.context-path=/api 已设置。据我所知,这不应该对控制器产生任何影响。

标签: java spring contextpath spring-restdocs


【解决方案1】:

您需要在传递给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())));
}

【讨论】:

  • 您的(src/main)代码可以使用属性server.servlet.context-path 设置上下文路径。令人失望的是,您的 (src/test) 代码需要在每个 mockMvc.perform() 调用中指定上下文路径。应该有一种方法可以在一个地方为所有测试用例做到这一点。
  • @Value("${spring.data.rest.basePath}") String basePath; 然后basePath+"/"
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-25
    • 2016-11-15
    • 2019-08-22
    • 2022-01-25
    • 1970-01-01
    • 2018-08-17
    • 2012-09-24
    • 1970-01-01
    相关资源
    最近更新 更多