org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders Java Examples

The following examples show how to use org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WorkbasketControllerRestDocumentation.java    From taskana with Apache License 2.0 7 votes vote down vote up
@Test
void getAllWorkbasketAccessItemsDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(
                      Mapping.URL_WORKBASKET_ID_ACCESSITEMS,
                      "WBI:100000000000000000000000000000000001"))
              .accept("application/hal+json")
              .header("Authorization", TEAMLEAD_1_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetAllWorkbasketAccessItemsDocTest",
              responseFields(allWorkbasketAccessItemsFieldDescriptors)));
}
 
Example #2
Source File: ItemResourceTest.java    From spring-auto-restdocs with Apache License 2.0 6 votes vote down vote up
/**
 * This test demonstrates that Spring REST Docs can be used in a Spring Auto REST Docs setup.
 * <p>
 * All Spring Auto REST Docs snippets are created as well because of the setup in {@link MockMvcBase}.
 * This is not a requirement and one could use a pure Spring REST Docs setup here.
 * <p>
 * The result of the manual documentation below ends up with section snippet using
 * classic Spring REST Docs' path-parameters.adoc and response-fields.adoc.
 * So there is no conflict and one is free to decide which snippets are included in the documentation.
 * <p>
 * RestDocumentationRequestBuilders.get is required for Spring REST Docs' pathParameters to work.
 * Spring AUTO Rest Docs works with both MockMvcRequestBuilders and RestDocumentationRequestBuilders.
 */
@Test
public void getItemWithRestDocs() throws Exception {
    mockMvc.perform(RestDocumentationRequestBuilders.get("/items/{id}", 1))
            .andExpect(status().isOk())
            .andDo(commonDocumentation(
                    pathParameters(
                            parameterWithName("id").description("ID of the item.")),
                    relaxedResponseFields(fieldWithPath("id")
                            .description("There are more fields but only the ID field is documented.")),
                    sectionBuilder().snippetNames(
                            AUTO_AUTHORIZATION,
                            PATH_PARAMETERS, // classic snippet
                            AUTO_REQUEST_PARAMETERS,
                            AUTO_REQUEST_FIELDS,
                            RESPONSE_FIELDS, // classic snippet
                            CURL_REQUEST, // classic snippet
                            HTTP_RESPONSE // classic snippet
                    ).build()));
}
 
Example #3
Source File: ApiControllerTests.java    From event-store-demo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testDeleteStoryOnBoard() throws Exception {

    UUID boardUuid = UUID.randomUUID();
    UUID storyUuid = UUID.randomUUID();
    when( this.service.deleteStory( any( UUID.class ), any( UUID.class ) ) ).thenReturn( ResponseEntity.accepted().build() );

    this.mockMvc.perform( RestDocumentationRequestBuilders.delete( "/boards/{boardUuid}/stories/{storyUuid}", boardUuid, storyUuid ) )
            .andDo( print() )
            .andExpect( status().isAccepted() )
            .andDo( document("delete-story",
                    pathParameters(
                            parameterWithName( "boardUuid" ).description( "The unique id of the board" ),
                            parameterWithName( "storyUuid" ).description( "The unique id of the story on the board to be deleted" )
                    )
            ));

    verify( this.service, times( 1 ) ).deleteStory( any( UUID.class ), any( UUID.class ) );

}
 
Example #4
Source File: TaskCommentControllerRestDocumentation.java    From taskana with Apache License 2.0 6 votes vote down vote up
@Test
void getAllTaskCommentsForSpecificTaskDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(
                      Mapping.URL_TASK_GET_POST_COMMENTS,
                      "TKI:000000000000000000000000000000000000"))
              .accept(MediaTypes.HAL_JSON)
              .header("Authorization", ADMIN_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetAllTaskCommentsForSpecificTaskDocTest",
              responseFields(allTaskCommentsFieldDescriptors)));
}
 
Example #5
Source File: WorkbasketControllerRestDocumentation.java    From taskana with Apache License 2.0 6 votes vote down vote up
@Test
void createWorkbasketDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.post(restHelper.toUrl(Mapping.URL_WORKBASKET))
              .contentType("application/json")
              .header("Authorization", TEAMLEAD_1_CREDENTIALS)
              .content(
                  "{\"key\" : \"asdasdasd\", \"name\" : \"Gruppenpostkorb KSC\", "
                      + "\"domain\" : \"DOMAIN_A\", \"type\" : \"GROUP\",   "
                      + "\"created\" : \"2018-02-01T11:00:00Z\",\r\n"
                      + "  \"modified\" : \"2018-02-01T11:00:00Z\"}"))
      .andExpect(MockMvcResultMatchers.status().isCreated())
      .andDo(
          MockMvcRestDocumentation.document(
              "CreateWorkbasketDocTest",
              requestFields(createWorkbasketFieldDescriptors),
              responseFields(workbasketFieldDescriptors)))
      .andReturn();
}
 
Example #6
Source File: AppRegistryDocumentation.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Test
public void appDefault() throws Exception {
    registerApp(ApplicationType.source, "http", "1.2.0.RELEASE");
    registerApp(ApplicationType.source, "http", "1.3.0.RELEASE");

    this.mockMvc.perform(RestDocumentationRequestBuilders
        .put("/apps/{type}/{name}/{version:.+}", ApplicationType.source, "http", "1.2.0.RELEASE").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isAccepted())
        .andDo(
            this.documentationHandler.document(
                pathParameters(
                    parameterWithName("type").description("The type of application. One of " + Arrays.asList(ApplicationType.values())),
                    parameterWithName("name").description("The name of the application"),
                    parameterWithName("version").description("The version of the application")
                )
            )
        );
    unregisterApp(ApplicationType.source, "http", "1.2.0.RELEASE");
    unregisterApp(ApplicationType.source, "http", "1.3.0.RELEASE");
}
 
Example #7
Source File: GetGreetingsDocTest.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate API documentation for GET /api/greetings.
 * 
 * @throws Exception Thrown if documentation generation failure occurs.
 */
@Test
public void documentGetGreetings() throws Exception {

    // Generate API Documentation
    final MvcResult result = this.mockMvc
            .perform(RestDocumentationRequestBuilders.get("/api/greetings").accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcRestDocumentation.document("get-greetings",
                    PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation.fieldWithPath("[].id").description(
                                    "The identifier. Used to reference specific greetings in API requests."),
                            PayloadDocumentation.fieldWithPath("[].referenceId")
                                    .description("The supplementary identifier."),
                            PayloadDocumentation.fieldWithPath("[].text").description("The text."),
                            PayloadDocumentation.fieldWithPath("[].version").description("The entity version."),
                            PayloadDocumentation.fieldWithPath("[].createdBy").description("The entity creator."),
                            PayloadDocumentation.fieldWithPath("[].createdAt")
                                    .description("The creation timestamp."),
                            PayloadDocumentation.fieldWithPath("[].updatedBy").description("The last modifier."),
                            PayloadDocumentation.fieldWithPath("[].updatedAt")
                                    .description("The last modification timestamp."))))
            .andReturn();

    // Perform a simple, standard JUnit assertion to satisfy PMD rule
    Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus());

}
 
Example #8
Source File: TaskanaEngineControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void getAllClassificationCategoriesDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(Mapping.URL_CLASSIFICATION_CATEGORIES))
              .accept("application/json")
              .header("Authorization", TEAMLEAD_1_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetAllClassificationCategoriesDocTest",
              responseFields(allClassificationCategoriesFieldDescriptors)));
}
 
Example #9
Source File: TaskanaEngineControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void getCurrentUserInfo() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(restHelper.toUrl(Mapping.URL_CURRENT_USER))
              .accept("application/json")
              .header("Authorization", TEAMLEAD_1_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetCurrentUserInfoDocTest", responseFields(currentUserInfoFieldDescriptors)));
}
 
Example #10
Source File: TaskanaEngineControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void getHistoryProviderIsEnabled() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(restHelper.toUrl(Mapping.URL_HISTORY_ENABLED))
              .accept("application/json")
              .header("Authorization", TEAMLEAD_1_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(MockMvcRestDocumentation.document("GetHistoryProviderIsEnabled"));
}
 
Example #11
Source File: ClassificationDefinitionControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void exportAllClassificationDefinitions() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(Mapping.URL_CLASSIFICATIONDEFINITIONS))
              .accept("application/json")
              .header("Authorization", TEAMLEAD_1_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "ExportClassificationDefinitionsDocTest",
              responseFields(classificationDefinitionsFieldDescriptors)));
}
 
Example #12
Source File: DeleteGreetingDocTest.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate API documentation for DELETE /api/greetings/{id}.
 * 
 * @throws Exception Thrown if documentation generation failure occurs.
 */
@Test
public void documentDeleteGreeting() throws Exception {

    // Generate API Documentation
    final MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders.delete("/api/greetings/{id}", 1))
            .andExpect(MockMvcResultMatchers.status().isNoContent())
            .andDo(MockMvcRestDocumentation.document("delete-greeting")).andReturn();

    // Perform a simple, standard JUnit assertion to satisfy PMD rule
    Assert.assertEquals("failure - expected HTTP status 204", 204, result.getResponse().getStatus());

}
 
Example #13
Source File: TaskCommentControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void getSpecificTaskCommentDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(
                      Mapping.URL_TASK_COMMENT, "TCI:000000000000000000000000000000000000"))
              .accept(MediaTypes.HAL_JSON)
              .header("Authorization", ADMIN_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetSpecificTaskCommentDocTest", responseFields(taskCommentFieldDescriptors)));
}
 
Example #14
Source File: TaskCommentControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void updateTaskCommentDocTest() throws Exception {
  URL url =
      new URL(
          restHelper.toUrl(Mapping.URL_TASK_COMMENT, "TCI:000000000000000000000000000000000000"));

  HttpURLConnection con = (HttpURLConnection) url.openConnection();
  con.setRequestMethod("GET");
  con.setRequestProperty("Authorization", ADMIN_CREDENTIALS);
  assertEquals(200, con.getResponseCode());

  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), UTF_8));
  String inputLine;
  StringBuilder content = new StringBuilder();
  while ((inputLine = in.readLine()) != null) {
    content.append(inputLine);
  }
  in.close();
  con.disconnect();
  String originalTaskComment = content.toString();
  String modifiedTaskComment =
      originalTaskComment.replace("some text in textfield", "updated text in textfield");

  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.put(
                  restHelper.toUrl(
                      Mapping.URL_TASK_COMMENT, "TCI:000000000000000000000000000000000000"))
              .header("Authorization", ADMIN_CREDENTIALS)
              .contentType(MediaTypes.HAL_JSON)
              .content(modifiedTaskComment))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "UpdateTaskCommentDocTest",
              requestFields(taskCommentFieldDescriptors),
              responseFields(taskCommentFieldDescriptors)));
}
 
Example #15
Source File: TaskCommentControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void createAndDeleteTaskCommentDocTest() throws Exception {

  String createTaskCommentContent =
      "{ \"taskId\" : \"TKI:000000000000000000000000000000000000\",\n"
          + "  \"textField\" : \"some text in textfield\"} ";

  MvcResult result =
      this.mockMvc
          .perform(
              RestDocumentationRequestBuilders.post(
                      restHelper.toUrl(
                          Mapping.URL_TASK_GET_POST_COMMENTS,
                          "TKI:000000000000000000000000000000000000"))
                  .contentType(MediaTypes.HAL_JSON)
                  .content(createTaskCommentContent)
                  .header("Authorization", ADMIN_CREDENTIALS))
          .andExpect(MockMvcResultMatchers.status().isCreated())
          .andDo(
              MockMvcRestDocumentation.document(
                  "CreateTaskCommentDocTest",
                  requestFields(createTaskCommentFieldDescriptors),
                  responseFields(taskCommentFieldDescriptors)))
          .andReturn();

  String resultContent = result.getResponse().getContentAsString();
  String newId =
      resultContent.substring(resultContent.indexOf("TCI:"), resultContent.indexOf("TCI:") + 40);

  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.delete(
                  restHelper.toUrl(Mapping.URL_TASK_COMMENT, newId))
              .header("Authorization", ADMIN_CREDENTIALS)) // admin
      .andExpect(MockMvcResultMatchers.status().isNoContent())
      .andDo(MockMvcRestDocumentation.document("DeleteTaskCommentDocTest"));
}
 
Example #16
Source File: ClassificationControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void getAllClassificationsDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_B")
              .accept("application/hal+json")
              .header("Authorization", TEAMLEAD_1_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetAllClassificationsDocTest",
              responseFields(allClassificationsFieldDescriptors)));
}
 
Example #17
Source File: ClassificationControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void getSpecificClassificationDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(
                      Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009"))
              .header("Authorization", TEAMLEAD_1_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetSpecificClassificationDocTest",
              responseFields(classificationFieldDescriptors)));
}
 
Example #18
Source File: GetGreetingDocTest.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate API documentation for GET /api/greetings/{id}.
 * 
 * @throws Exception Thrown if documentation generation failure occurs.
 */
@Test
public void documentGetGreeting() throws Exception {

    // Generate API Documentation
    final MvcResult result = this.mockMvc
            .perform(RestDocumentationRequestBuilders
                    .get("/api/greetings/{id}", "0").accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcRestDocumentation.document("get-greeting",
                    RequestDocumentation.pathParameters(
                            RequestDocumentation.parameterWithName("id").description("The greeting identifier.")),
                    PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation.fieldWithPath("id")
                                    .description(
                                            "The identifier. Used to reference specific greetings in API requests.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("referenceId")
                                    .description("The supplementary identifier.").type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("text").description("The text.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("version").description("The entity version.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.")
                                    .type(JsonFieldType.STRING).optional(),
                            PayloadDocumentation.fieldWithPath("updatedAt")
                                    .description("The last modification timestamp.").type(JsonFieldType.STRING)
                                    .optional())))
            .andReturn();

    // Perform a simple, standard JUnit assertion to satisfy PMD rule
    Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus());

}
 
Example #19
Source File: ClassificationControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void classificationSubsetDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(
                      Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009"))
              .header("Authorization", TEAMLEAD_1_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "ClassificationSubset", responseFields(classificationSubsetFieldDescriptors)));
}
 
Example #20
Source File: ClassificationControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void updateClassificationDocTest() throws Exception {
  URL url =
      new URL(
          restHelper.toUrl(
              Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009"));
  HttpURLConnection con = (HttpURLConnection) url.openConnection();
  con.setRequestMethod("GET");
  con.setRequestProperty("Authorization", TEAMLEAD_1_CREDENTIALS);
  assertEquals(200, con.getResponseCode());

  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), UTF_8));
  String inputLine;
  StringBuilder content = new StringBuilder();
  while ((inputLine = in.readLine()) != null) {
    content.append(inputLine);
  }
  in.close();
  con.disconnect();
  String modifiedTask = content.toString();

  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.put(
                  restHelper.toUrl(
                      Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009"))
              .header("Authorization", TEAMLEAD_1_CREDENTIALS)
              .contentType("application/json")
              .content(modifiedTask))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "UpdateClassificationDocTest",
              requestFields(classificationFieldDescriptors),
              responseFields(classificationFieldDescriptors)));
}
 
Example #21
Source File: TaskHistoryEventControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
public void getAllTaskHistoryEventDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  "http://127.0.0.1:" + port + "/api/v1/task-history-event?page=1&page-size=3")
              .accept("application/hal+json")
              .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetAllTaskHistoryEventDocTest",
              responseFields(allTaskHistoryEventFieldDescriptors)));
}
 
Example #22
Source File: UpdateGreetingDocTest.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate API documentation for PUT /api/greetings/{id}.
 * 
 * @throws Exception Thrown if documentation generation failure occurs.
 */
@Test
public void documentUpdateGreeting() throws Exception {

    // Generate API Documentation
    final MvcResult result = this.mockMvc.perform(RestDocumentationRequestBuilders.put("/api/greetings/{id}", 1)
            .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(REQUEST_BODY))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcRestDocumentation.document("update-greeting",
                    RequestDocumentation.pathParameters(
                            RequestDocumentation.parameterWithName("id").description("The greeting identifier.")),
                    PayloadDocumentation.relaxedRequestFields(PayloadDocumentation.fieldWithPath("text")
                            .description("The text.").type(JsonFieldType.STRING)),
                    PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation
                                    .fieldWithPath("id")
                                    .description(
                                            "The identifier. Used to reference specific greetings in API requests.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("referenceId")
                                    .description("The supplementary identifier.").type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("text").description("The text.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("version").description("The entity version.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.")
                                    .type(JsonFieldType.STRING).optional(),
                            PayloadDocumentation.fieldWithPath("updatedAt")
                                    .description("The last modification timestamp.").type(JsonFieldType.STRING)
                                    .optional())))
            .andReturn();

    // Perform a simple, standard JUnit assertion to satisfy PMD rule
    Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus());

}
 
Example #23
Source File: TaskHistoryEventControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
public void getSpecificTaskHistoryEventDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  "http://127.0.0.1:" + port + "/api/v1/task-history-event/1")
              .accept("application/hal+json")
              .header("Authorization", "Basic dGVhbWxlYWRfMTp0ZWFtbGVhZF8x"))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetSpecificTaskHistoryEventDocTest",
              responseFields(taskHistoryEventFieldDescriptors)));
}
 
Example #24
Source File: SpeakerControllerTest.java    From springrestdoc with MIT License 5 votes vote down vote up
@Test
public void testGetSpeaker() throws Exception {
    //Given
    Speaker josh = given.speaker("Josh Long").company("Pivotal").save();
    Speaker noiseData = given.speaker("Noise").company("Noise").save();

    //When
    ResultActions actions = mockMvc.perform(RestDocumentationRequestBuilders.get("/speakers/{id}", josh.getId()))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name", is("Josh Long")))
            .andExpect(jsonPath("$.company", is("Pivotal")))
            .andDo(print());

    actions.andDo(document("{class-name}/{method-name}",
            responseFields(
                    fieldWithPath("name").description("Speaker's name"),
                    fieldWithPath("status").description("Speaker's name"),
                    fieldWithPath("company").description("Speaker's name"),
                    subsectionWithPath("_links").description("<<resources-tags-links, Links>> to Speakers HATEOAS")
            ),
            links(halLinks(),
                    linkWithRel("self").description("Link to self"),
                    linkWithRel("topics").description("Link to speaker's topics.")),
            pathParameters(
                    parameterWithName("id").description("Required identifier of Speaker")
            )
    ));
}
 
Example #25
Source File: SpeakerControllerTest.java    From springrestdoc with MIT License 5 votes vote down vote up
@Test
public void testDeleteSpeaker() throws Exception {
    //Given
    Speaker speakerToDelete = given.speaker("TO_DELETE").company("COMPANY").save();

    //When
    ResultActions actions = mockMvc.perform(RestDocumentationRequestBuilders.delete("/speakers/{id}", speakerToDelete.getId()))
            .andDo(print());

    //Then
    actions.andExpect(status().isNoContent());
    actions.andDo(document("{class-name}/{method-name}"));
    assertEquals(0, speakerRepository.count());
}
 
Example #26
Source File: SpeakerControllerTest.java    From springrestdoc with MIT License 5 votes vote down vote up
@Test
public void testCreateSpeaker_created() throws Exception {
    // Given
    SpeakerDto requestDto = given.speakerDto("Josh Long").company("Pivotal").build();
    String requestBody = given.asJsonString(requestDto);

    // When
    ResultActions action = mockMvc.perform(RestDocumentationRequestBuilders.post("/speakers")
            .content(requestBody))
            .andDo(print());

    // Then
    assertEquals(1, speakerRepository.count());
    Speaker savedSpeaker = speakerRepository.findByName("Josh Long").get();

    assertEquals(requestDto.getName(), savedSpeaker.getName());
    assertEquals(requestDto.getCompany(), savedSpeaker.getCompany());

    action.andExpect(status().isCreated())
            .andExpect(header().string("Location", endsWith("/speakers/" + savedSpeaker.getId())));

    ConstrainedFields constrainedFields = new ConstrainedFields(SpeakerDto.class);

    action.andDo(document("{class-name}/{method-name}",
            requestFields(
                    attributes(key("title").value("SpeakerDTO Constrains")),
                    constrainedFields.name("name").description("The speaker's name."),
                    constrainedFields.name("company").description("The company speaker is working on.")
            ),
            responseHeaders(
                    headerWithName("Location").description("URI path to created resource."))));
}
 
Example #27
Source File: CreateGreetingDocTest.java    From skeleton-ws-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate API documentation for POST /api/greetings.
 * 
 * @throws Exception Thrown if documentation generation failure occurs.
 */
@Test
public void documentCreateGreeting() throws Exception {

    // Generate API Documentation
    final MvcResult result = this.mockMvc
            .perform(RestDocumentationRequestBuilders.post("/api/greetings").contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON).content(REQUEST_BODY))
            .andExpect(MockMvcResultMatchers.status().isCreated())
            .andDo(MockMvcRestDocumentation.document("create-greeting",
                    PayloadDocumentation.relaxedRequestFields(PayloadDocumentation.fieldWithPath("text")
                            .description("The text.").type(JsonFieldType.STRING)),
                    PayloadDocumentation.relaxedResponseFields(
                            PayloadDocumentation
                                    .fieldWithPath("id")
                                    .description(
                                            "The identifier. Used to reference specific greetings in API requests.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("referenceId")
                                    .description("The supplementary identifier.").type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("text").description("The text.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("version").description("The entity version.")
                                    .type(JsonFieldType.NUMBER),
                            PayloadDocumentation.fieldWithPath("createdBy").description("The entity creator.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("createdAt").description("The creation timestamp.")
                                    .type(JsonFieldType.STRING),
                            PayloadDocumentation.fieldWithPath("updatedBy").description("The last modifier.")
                                    .type(JsonFieldType.STRING).optional(),
                            PayloadDocumentation.fieldWithPath("updatedAt")
                                    .description("The last modification timestamp.").type(JsonFieldType.STRING)
                                    .optional())))
            .andReturn();

    // Perform a simple, standard JUnit assertion to satisfy PMD rule
    Assert.assertEquals("failure - expected HTTP status 201", 201, result.getResponse().getStatus());

}
 
Example #28
Source File: WorkbasketControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void workbasketSubsetDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(
                      Mapping.URL_WORKBASKET_ID, "WBI:100000000000000000000000000000000001"))
              .accept("application/hal+json")
              .header("Authorization", TEAMLEAD_1_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "WorkbasketSubset", responseFields(workbasketSubsetFieldDescriptors)));
}
 
Example #29
Source File: AbstractPagingControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void commonSummaryResourceFieldsDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?page=2&page-size=5")
              .header("Authorization", TEAMLEAD_1_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "CommonSummaryResourceFields", responseFields(pagingFieldDescriptors)));
}
 
Example #30
Source File: TaskControllerRestDocumentation.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void getAllTasksDocTest() throws Exception {
  this.mockMvc
      .perform(
          RestDocumentationRequestBuilders.get(
                  restHelper.toUrl(Mapping.URL_TASKS) + "?por.type=VNR&por.value=22334455")
              .accept("application/hal+json")
              .header("Authorization", ADMIN_CREDENTIALS))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andDo(
          MockMvcRestDocumentation.document(
              "GetAllTasksDocTest", responseFields(allTasksFieldDescriptors)));
}