Spring REST Docs: как заменить параметры запроса - PullRequest
0 голосов
/ 08 апреля 2020

Мы хотим заменить параметр запроса.

В коде статус активен. Я использую метод maskStatus () для маскировки статуса.

this.mockMvc
        .perform(RestDocumentationRequestBuilders.get("/helloworld")
                .accept(MediaType.APPLICATION_JSON)
                .param("status", "active"))
        .andExpect(status().isOk())
        .andDo(document("{class-name}/{method-name}",
                Preprocessors.preprocessRequest(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Accept"),
                        maskStatus()),
                RequestDocumentation.requestParameters(RequestDocumentation.parameterWithName("status").description("The status"))

        ));

В сгенерированном http-request.ado c мы хотим, чтобы статус был "* status *":

[source,http,options="nowrap"]
----
GET /missioncontrol/v1/helloworld?status=*status* HTTP/1.1
Host: localhost:8080
----

Но фактический результат:

[source,http,options="nowrap"]
----
GET /missioncontrol/v1/helloworld?status=active&status=*status* HTTP/1.1
Host: localhost:8080

----

Код:

@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
public class TestControllerTest {

    @Rule
    public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation( "target/snippets");

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    protected MockMvc mockMvc;


    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
                .apply(MockMvcRestDocumentation.documentationConfiguration(this.restDocumentation))     
                .addFilter(springSecurityFilterChain)
                .build();
    }

    @Test
    public void hellWorldTest() throws Exception {
        this.mockMvc
        .perform(RestDocumentationRequestBuilders.get("/helloworld")
                .accept(MediaType.APPLICATION_JSON)
                .param("status", "active"))
        .andExpect(status().isOk())
        .andDo(document("{class-name}/{method-name}",
                Preprocessors.preprocessRequest(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Accept"),
                        maskStatus()),
                RequestDocumentation.requestParameters(RequestDocumentation.parameterWithName("status").description("The status"))

        ));
    }

    private OperationPreprocessor maskStatus() {
        return new StatusMaskingPreprocessor();
    }

    private static class StatusMaskingPreprocessor implements OperationPreprocessor {

        @Override
        public OperationRequest preprocess(OperationRequest request) {
            Parameters parameters = new Parameters();
            parameters.set("status", "*status*");
            return new OperationRequestFactory().create(request.getUri(),
                    request.getMethod(), request.getContent(), request.getHeaders(),
                    parameters, request.getParts());
        }

        @Override
        public OperationResponse preprocess(OperationResponse response) {
            return response;
        }

    }

Вопросы: Мы хотим заменить статус. Но это не работает, и он просто добавляет новое назначение. Почему?

Другие способы, которые я пробовал:

@Test
    public void hellWorldTest() throws Exception {
        this.mockMvc
        .perform(RestDocumentationRequestBuilders.get("/helloworld")
                .accept(MediaType.APPLICATION_JSON)
                .param("status", "active"))
        .andExpect(status().isOk())
        .andDo(document("{class-name}/{method-name}",
                Preprocessors.preprocessRequest(Preprocessors.prettyPrint(), Preprocessors.removeHeaders("Accept"),
                        Preprocessors.modifyParameters().remove("status").set("status", "*status*")),
                RequestDocumentation.requestParameters(RequestDocumentation.parameterWithName("status").description("The status"))

        ));
    }

Результат по-прежнему "GET / helloworld? Status = active & status = * status * HTTP / 1.1"

Кто-нибудь знает, как заменить параметры запроса?

Заранее спасибо.

1 Ответ

0 голосов
/ 23 апреля 2020

Вы делаете запрос GET и, следовательно, status будет частью строки запроса URI запроса. Проблема заключается в том, что препроцессоры (и ваша пользовательская реализация, и встроенная в REST Docs) изменяют параметры, но не вносят соответствующее изменение в URI. Вы можете решить эту проблему, обновив StatusMaskingPreprocessor для изменения URI, а также параметров.

Я открыл Spring REST Docs документ , чтобы посмотреть, сможем ли мы исправить это в универсальный способ.

...