1

O. 我正在使用 Spring boot server.context-path=/myRoot。然后我有一个处理@RequestMapping("/some/path") 的@RestController。在控制器单元测试中,我使用的是 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;
    }

}
4

0 回答 0