O.我使用的是Spring boot server.context-path = / myRoot . 然后我有一个@RestController来处理@RequestMapping(“/ some / path”) . 在控制器单元测试我正在使用MockMvc .

@Test
    public void shouldGetSuccessfulHttpResponseForBasket() throws Exception {
        //Given
        String requestURL = "/some/path";
        //When
        MvcResult result = getMockMvc().perform(get(requestURL))
        //Then
                .andExpect(status().isOk());
        String content = result.getResponse().getContentAsString();
        assertNotEquals("Content should not be empty", "", content);
    }

所以我的问题是内容空洞 . 这是因为我的单元测试不使用server.context-path = / myRoot . 因此,如果我使用此URL“/ myRoot / some / path”,http状态为400,因为它找不到匹配的处理程序 . 如果我使用此URL“/ some / path”,http状态为200,但内容为空(不应该) . 如果我使用@RequestMapping(“/ myRoot”)注释我的控制器,它将使用此URL“/ myRoot / some / path” . 但那时我的申请将无法正常运作 . 在最后一种情况下,我将不得不使用此URL“/ myRoot / myRoot / some / path”来获取我的服务的响应 .

所以理想的解决方案是摆脱server.context-path = / myRoot . 这是不可能的,因为应用程序依赖于该属性 . 关于如何解决这个问题的任何想法?

提前致谢 .

更新:

这是我的基类 . 我的测试类正在扩展这个 .

/**
 * Sets up and gets the mvc test support available in the mock context.
 */
public abstract class MvcTestCase {

    /** The spring mock web context. */
    @Autowired
    private WebApplicationContext webContext;

    /**
     * The service that creates a mock context to test against the front Controller.
     */
    private MockMvc mockMvc;

    /**
     * Sets up the service that creates a mock context to test against the front Controller.
     * 
     * @throws Exception thrown when set up fails.
     */
    @Before
    public void setupMockContext() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webContext)
                .build();
    }

    /**
     * Gets the mock mvc test support.
     * 
     * @return The entry point for server-side Spring MVC test support.
     */
    public MockMvc getMockMvc() {
        return mockMvc;
    }

}