【问题标题】:Spring Rest Docs How do I include the application name in my snippets or .adoc fileSpring Rest Docs 如何在我的代码片段或 .adoc 文件中包含应用程序名称
【发布时间】:2016-03-25 10:30:41
【问题描述】:

我正在尝试将 Spring Rest Docs 包含在 Spring Boot 应用程序中,并设法生成了一个简单的 asciidoc HTML 文件,该文件显示了应用程序根目录“/”的请求路径。问题是sn -p中的请求URL不包含应用名称?例如,我的应用程序称为“myservice”,因此我希望将根“/”请求路径记录为

$ curl 'http://localhost:8080/myservice/'

我只能生成

$ curl 'http://localhost:8080/'

我是 Spring Rest Docs 的新手,无法弄清楚如何在记录的 URL 中包含应用程序名称。它是在 asccidoctor 的 maven 插件中、在测试类的 @before 或 @Test 方法中还是在 .adoc 文件中作为“包含”标签的一部分设置的?

【问题讨论】:

    标签: spring-mvc spring-boot asciidoctor spring-restdocs


    【解决方案1】:

    这是mentioned in the documentation

    要配置请求的上下文路径,请在 MockHttpServletRequestBuilder 上使用 contextPath 方法。

    在您的示例中,您的应用程序称为myservice,而您正在请求/。您的 MockMvc 调用应如下所示:

    this.mockMvc.perform(get("/myservice/").contextPath("/myservice"))
            .andExpect(status().isOk())
            .andDo(document("index"));
    

    【讨论】:

    • 使用上述解决方案我得到以下错误:equestURI [/] does not start with contextPathstackoverflow.com/questions/35435631/…你能帮帮我吗?
    • 正如 Andy 上面解释的(以及下面的示例),您应该在 URI 和 contextPath 方法中添加上下文路径。
    【解决方案2】:

    我让它工作的方式是将上下文路径包含为其余 URI 的一部分,并在 RequestBuilder 上调用 contextPath。这是工作示例。在我的示例中,“api”是上下文根。我必须将它包含在请求中,并在 RequestBuilder 上调用 contextPath 方法并进行设置。

    @Andy Wilkinson:我知道这可能是在重复您所说的内容,但我认为对于像我这样的人来说,一个完整的工作示例会更清楚:)

    @RunWith(MockitoJUnitRunner.class)
    public class UserControllerTest {
    
    
        private UserController controller;
    
        private MockMvc mockMvc;
    
        @Rule
        public RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
    
        @Before
        public void setUp() {
    
            controller = new UserController();
            mockMvc = standaloneSetup(controller).apply(documentationConfiguration(this.restDocumentation)).build();
        }
    
        @Test
        public void testUsers() throws Exception {
    
            this.mockMvc.perform(get("/api/users/{userId}","1234").contextPath("/api"))
                    .andExpect(status().isOk())
                    .andDo(document("user-information", pathParameters(
                            parameterWithName("userId").description("user id.")
                    ), responseFields(
                            fieldWithPath("firstName").description("first name of the user. "),
                            fieldWithPath("lastName").description("Last name of the user. ")
    
                    )))
                    .andDo(print());
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 2012-08-27
      相关资源
      最近更新 更多