2016-02-16 33 views
1

我嘗試設置的彈簧安置上下文路徑使用下面的代碼片段嘲笑:彈簧安置模擬上下文路徑

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); 
    } 
} 
+0

嘗試後您的控制器 – Abdelhak

+0

請參閱編輯。爲什麼downvote?請記住'server.context-path =/api'已設置。據我所知,這應該不會對控制器產生任何影響。 –

回答

3

您需要在您傳遞到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()))); 
}