标签: spring-restdocs

Spring REST模拟上下文路径

我尝试使用以下代码片段为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())));
}
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

java.lang.IllegalArgumentException: requestURI [/] does not start with contextPath [/api]
Run Code Online (Sandbox Code Playgroud)

怎么了? 是否可以在代码中的单个位置指定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, …
Run Code Online (Sandbox Code Playgroud)

java spring contextpath spring-restdocs

3
推荐指数
2
解决办法
3289
查看次数

Spring REST 文档:如何替换参数

在我的单元测试中,我们发现

this.mockMvc
  .perform(post("/authenticate")
    .contentType(MediaType.APPLICATION_FORM_URLENCODED)
    .param("username", "user@example.com")
    .param("password", "superSecretPassword"))
  .andExpect(status().isOk())
  .andDo(document("preprocessed-request",
    preprocessRequest(replacePattern(Pattern.compile("superSecretPassword"), "XXX"))));
Run Code Online (Sandbox Code Playgroud)

参见 Spring REST 文档文档

build/generated-snippets/preprocessed-request/http-request.adoc与内容一起生成

[source,http]
----
POST /authenticate HTTP/1.1
Content-Type: application/x-www-form-urlencoded

username=user%40example.com&password=superSecretPassword
----
Run Code Online (Sandbox Code Playgroud)

但我希望密码会因为 replacePattern() 被屏蔽:

[source,http]
----
POST /authenticate HTTP/1.1
Content-Type: application/x-www-form-urlencoded

username=user%40example.com&password=XXX
----
Run Code Online (Sandbox Code Playgroud)

我能做什么?

java spring spring-mvc spring-restdocs

2
推荐指数
1
解决办法
2178
查看次数

如何使用spring-restdocs记录http错误代码

有没有办法使用spring-restdocs记录http错误代码?我在http://docs.spring.io/spring-restdocs/docs/current/reference/html5/上没有发现任何相同的内容.

任何有关示例的帮助将不胜感激.

此致,苏里亚

spring-restdocs

2
推荐指数
1
解决办法
785
查看次数

是否可以使用带有spock的spring rest docs

我在我的java应用程序中使用spock和groovy构建了测试用例.是否可以在不使用模拟mvc或restassured的情况下将spring rest docs添加到此项目中

这是我的项目剪辑

import groovyx.net.http.RESTClient;
import spock.lang.Specification;

class FindIdeasSpec extends Specification{
def host ="http://www.localhost.com:8080/v1/"
def path = "communities/"
def client = new RESTClient(host)
def id = 1

def "verify the links"() {

    when: "request ideas list"
    def response = client.get(path: path + id + '/ideas')

    then: "returns parent and self link"
    with(response) {
        status == 200
        data.links.rel == ['self']
        data.links.href[0] == host + path + id + '/ideas'
    }
}
Run Code Online (Sandbox Code Playgroud)

java groovy spock spring-restdocs

2
推荐指数
1
解决办法
722
查看次数

找不到 Spring rest 文档生成的内容

我正在使用 Spring REST Docs 为我们的 API 生成文档。我已经从这里的教程http://docs.spring.io/spring-restdocs/docs/current/reference/html5/添加了所有内容到 build.gradle

ext {
    snippetsDir = file('build/generated-snippets')
}

test {
    outputs.dir snippetsDir
}

asciidoctor {
    attributes 'snippets': snippetsDir
    inputs.dir snippetsDir
    outputDir "build/asciidoc"
    dependsOn test
    sourceDir 'src/main/asciidoc'
}

jar {
    dependsOn asciidoctor
    from ("${asciidoctor.outputDir}/html5") {
        into 'static/docs'
    }
}
Run Code Online (Sandbox Code Playgroud)

在我这样做之后,gradle build我可以看到在build/asciidoc目录中生成了文件,也在build/generated-snippets.

但是,当我从 IDEA gradle 任务运行bootRun并尝试访问 localhost:8080/docs/index.html 时,我找不到 404。只是为了测试,我尝试将一些index.html文件放在resources/static目录下,然后执行bootRun,我可以访问localhost:8080/index.html文件在那之后。

如果我打开我的 .jar 文件,我可以看到目录下的静态文件,BOOT-INF/classes/static/docs因此它们被打包到 jar 中。

也许有人有同样的问题?

java spring spring-mvc spring-restdocs

2
推荐指数
1
解决办法
1663
查看次数

不推荐使用RestDocumentation类,我应该使用什么?

该文档org.springframework.restdocs.RestDocumentation,它已被弃用状态.

我试图在这样的JUnit测试中使用该类:

@Rule
public RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
Run Code Online (Sandbox Code Playgroud)

我应该使用什么课?

java spring spring-restdocs

2
推荐指数
1
解决办法
272
查看次数

如何在spring RestDoc(asciidoc)中折叠TOC(目录)?

我使用过 SpringRestDoc 并且想要折叠目录。

下面我的index.adoc

= Service Rest Docs API Document
:doctype: book
:icons: font
:source-highlighter: highlightjs
:toc2: left
:theme: flatly
:toclevels: 1
:sectlinks:

[[introduction]]

== information

----
Spring Rest Document
----

...
Run Code Online (Sandbox Code Playgroud)

谢谢,

asciidoc spring-boot spring-restdocs

2
推荐指数
1
解决办法
1678
查看次数

注释中的Spring-restdocs字段描述

是否可以使用注释(在字段级别)为字段提供描述?

我知道我可以使用description方法

.andDo(document("index", responseFields( 
            fieldWithPath("contact").description("The user's contact details"), 
Run Code Online (Sandbox Code Playgroud)

但是我更希望将该描述与字段定义一起放在我的响应对象中。

class IndexResponse {
 //The user's contact details
 String contract;
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以生成约束描述(http://docs.spring.io/spring-restdocs/docs/current/reference/html5/#_using_constraint_descriptions_in_genic_snippets),但是它仅生成验证注释的描述。

我正在寻找来自Swagger的https://github.com/swagger-api/swagger-core/wiki/Annotations#apimodelproperty之类的东西。

spring-restdocs spring-auto-restdocs

1
推荐指数
2
解决办法
668
查看次数

我如何使用Spring Docs记录java.util.Map

想象一下我下一堂课

public class MyDTO implements Serializable {
    private static final long serialVersionUID = 1L;

    private String id;
    private Map<String, String> names;

    // public Getters and Setters
}
Run Code Online (Sandbox Code Playgroud)

当我使用下一个代码通过Spring对其进行记录时

private static FieldDescriptor[] myDTOFields() {
  return new FieldDescriptor[] { 
    fieldWithPath("id").description("id description"),
    fieldWithPath("names").description("Names description") };
}
Run Code Online (Sandbox Code Playgroud)

它不起作用,并且出现错误。

org.springframework.restdocs.snippet.SnippetException:有效负载的以下部分未记录:

{
  "names" : {
    "en" : "test"
  }
}
Run Code Online (Sandbox Code Playgroud)

那我怎么用spring docs记录java.util.Map?

谢谢 :)

spring spring-mvc spring-boot spring-restdocs

1
推荐指数
1
解决办法
498
查看次数

如何使用 Spring Rest 文档记录对象列表

我正在使用 Spring Rest Docs 来记录我的 REST API。我在集成测试中使用mockMVC,并且想记录以下 JSON 响应:

GET /api/v1/customers/3b658b39-4264-4995-99d8-90a1672a75a7

{
    "id": "3b658b39-4264-4995-99d8-90a1672a75a7",
    "name": "Foo",
    "nickname": "Bar",
    "phones": [
        {
            "id": "6ca3a963-bacb-4770-a470-5902b4a17b77", 
            "alias": "Personal Phone 1",   
            "countryCode": "55",
            "areaCode": "34",
            "number": "99999-9999"
        },
        {
            "id": "f3a3726b-b5f8-4652-a044-7bf3d95a37de",
            "alias": "Personal Phone 2",    
            "countryCode": "55",
            "areaCode": "34",
            "number": "88888-8888"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我如何记录上面的电话列表?您可以使用以下代码片段,该代码片段使用 Spring REST 文档来记录此 API 操作:

this.mockMvc.perform(
    get("/api/v1/customers/3b658b39-4264-4995-99d8-90a1672a75a7")
       .accept(APPLICATION_JSON))
       .andExpect(status().isOk())
           .andDo(document("customer").withResponseFields(
               fieldWithPath("id").description("Unique identifier"),
               fieldWithPath("name").description("Customer full name"),
               fieldWithPath("nickname").description("How the customer wants to be called")));
Run Code Online (Sandbox Code Playgroud)

java documentation spring spring-restdocs

1
推荐指数
1
解决办法
3851
查看次数

如何使用 spring restdocs 记录包含 JSON 对象的请求正文

我正在使用 spring boot 2 来实现 REST API 服务,并想用 restdocs 记录它。

终点

POST /api/tags
Run Code Online (Sandbox Code Playgroud)

带有请求正文

{"name":"Some Tag", "description":"This is Some Tag"}
Run Code Online (Sandbox Code Playgroud)

用于添加创建新标签。我已经查看了 restdocs 文档,但仍然找不到记录请求正文的 JSON 字段的方法,任何人都可以帮我填写缺少的部分“......”。

TagRequest request = new TagRequest();
request.setName("Some Tag");
request.setDescription("This is Some Tag");
client.post().uri("/api/tags").body(BodyInserters.fromObject(request)).exchange()
        .expectStatus().isOk().expectBody(Integer.class)
        .consumeWith(document("add-tag", ...... )));
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-restdocs

1
推荐指数
1
解决办法
1908
查看次数

如何使用MockMvc在响应主体中格式化Spring REST Docs

我用Spring REST Docs编写API文档。

代码示例:

@Override
public void getById(String urlTemplate, PathParametersSnippet pathParametersSnippet, Object... urlVariables) throws Exception {
    resultActions = mockMvc.perform(get(urlTemplate, urlVariables)
            .principal(principal)
            .contentType(APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(print());

    // do..
}
Run Code Online (Sandbox Code Playgroud)

但是问题是测试结果只能在一行中回答。而且,了解返回数据的结构非常困难。

响应示例:

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {"creator":null,"modifier":null,"modificationTime":null,"creationTime":null,"id":100,"deleted":false,"name":"Name","description":null,"report":[{"creator":"System","modifier":"System","modificationTime":"2019-01-30T14:21:50","creationTime":"2019-01-30T14:21:50","id":1,"name":"Form name","reportType":{"creator":"System","modifier":"System","modificationTime":"2019-01-30T14:21:50","creationTime":"2019-01-30T14:21:50","id":1,"deleted":false,"name":"Raport"},"unmodifiable":true}]}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
Run Code Online (Sandbox Code Playgroud)

此外,我根据收到的答案生成文档,并且在文档中还使用未格式化的JSON

我究竟做错了什么?如何启用JSON格式?

java spring spring-mvc-test spring-restdocs

1
推荐指数
1
解决办法
1140
查看次数

如何从示例 curl 中完全删除端口号

我正在记录一个 Web API,我需要 curl 和 httpie 示例才能对我们的端点进行有效调用。问题是示例 curl 片段包含一个端口号,我看不出有任何方法可以摆脱它。我看到如何设置端口号,但我不知道如何完全摆脱它。

我错过了什么吗?这似乎是一个常见的用例。

在此先感谢您的帮助!

spring-restdocs

0
推荐指数
1
解决办法
394
查看次数