Java Code Examples for io.restassured.response.Response#as()

The following examples show how to use io.restassured.response.Response#as() . 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: TaskRestServiceInteractionTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private void verifyTaskAttachments(List<Attachment> mockTaskAttachments, Response response) {
  List list = response.as(List.class);
  assertEquals(1, list.size());

  LinkedHashMap<String, String> resourceHashMap = (LinkedHashMap<String, String>) list.get(0);

  String returnedId = resourceHashMap.get("id");
  String returnedTaskId = resourceHashMap.get("taskId");
  String returnedName = resourceHashMap.get("name");
  String returnedType = resourceHashMap.get("type");
  String returnedDescription = resourceHashMap.get("description");
  String returnedUrl = resourceHashMap.get("url");

  Attachment mockAttachment = mockTaskAttachments.get(0);

  assertEquals(mockAttachment.getId(), returnedId);
  assertEquals(mockAttachment.getTaskId(), returnedTaskId);
  assertEquals(mockAttachment.getName(), returnedName);
  assertEquals(mockAttachment.getType(), returnedType);
  assertEquals(mockAttachment.getDescription(), returnedDescription);
  assertEquals(mockAttachment.getUrl(), returnedUrl);
}
 
Example 2
Source File: TaskRestServiceInteractionTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private void verifyTaskComments(List<Comment> mockTaskComments, Response response) {
  List list = response.as(List.class);
  assertEquals(1, list.size());

  LinkedHashMap<String, String> resourceHashMap = (LinkedHashMap<String, String>) list.get(0);

  String returnedId = resourceHashMap.get("id");
  String returnedUserId = resourceHashMap.get("userId");
  String returnedTaskId = resourceHashMap.get("taskId");
  Date returnedTime = DateTimeUtil.parseDate(resourceHashMap.get("time"));
  String returnedFullMessage = resourceHashMap.get("message");

  Comment mockComment = mockTaskComments.get(0);

  assertEquals(mockComment.getId(), returnedId);
  assertEquals(mockComment.getTaskId(), returnedTaskId);
  assertEquals(mockComment.getUserId(), returnedUserId);
  assertEquals(mockComment.getTime(), returnedTime);
  assertEquals(mockComment.getFullMessage(), returnedFullMessage);
}
 
Example 3
Source File: LiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenAddnewBook_thenSuccess() {
    final Book book = new Book();
    book.setTitle("How to spring cloud");
    book.setAuthor("Baeldung");

    // request the protected resource
    final Response bookResponse = RestAssured.given()
        .auth()
        .form("admin", "admin", formConfig)
        .and()
        .contentType(ContentType.JSON)
        .body(book)
        .post(ROOT_URI + "/book-service/books");
    final Book result = bookResponse.as(Book.class);
    Assert.assertEquals(HttpStatus.OK.value(), bookResponse.getStatusCode());
    Assert.assertEquals(book.getAuthor(), result.getAuthor());
    Assert.assertEquals(book.getTitle(), result.getTitle());

}
 
Example 4
Source File: LiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenAddnewRating_thenSuccess() {

    final Rating rating = new Rating();
    rating.setBookId(1L);
    rating.setStars(4);

    // request the protected resource
    final Response ratingResponse = RestAssured.given()
        .auth()
        .form("admin", "admin", formConfig)
        .and()
        .contentType(ContentType.JSON)
        .body(rating)
        .post(ROOT_URI + "/rating-service/ratings");
    final Rating result = ratingResponse.as(Rating.class);
    Assert.assertEquals(HttpStatus.OK.value(), ratingResponse.getStatusCode());
    Assert.assertEquals(rating.getBookId(), result.getBookId());
    Assert.assertEquals(rating.getStars(), result.getStars());
}
 
Example 5
Source File: JdbcComponentTestIT.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSchema_wrongSql() throws java.io.IOException {
    // given

    UiSpecsPropertiesDto datasetConnectionInfo = new UiSpecsPropertiesDto();
    datasetConnectionInfo.setProperties(mapper.readValue(
            getClass().getResourceAsStream("jdbc_data_set_properties_no_schema_wrong_table_name.json"), ObjectNode.class));
    datasetConnectionInfo.setDependencies(singletonList(getJdbcDataStoreProperties()));

    // when
    final Response responseApiError = given().body(datasetConnectionInfo)
                                 .contentType(APPLICATION_JSON_UTF8_VALUE) //
                                 .accept(APPLICATION_JSON_UTF8_VALUE)
                                 .post(getVersionPrefix() + "/runtimes/schema");
    responseApiError.then().statusCode(400).log().ifValidationFails();
    ApiError response = responseApiError.as(ApiError.class);

    // then
    assertEquals("TCOMP_JDBC_SQL_SYNTAX_ERROR", response.getCode());
    assertEquals("Table/View 'TOTO' does not exist.", response.getMessage());
}
 
Example 6
Source File: WorldClockApiTest.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 6 votes vote down vote up
@Test
@Disabled
public void testNow() throws URISyntaxException {
    Response response = given()
            .when()
            .get("/data/time/now")
            .andReturn();

    Assertions.assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode());
    String replyString = response.body().asString();
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    System.out.println(reply);
    Now numbers = response.as(Now.class);
    System.out.println(numbers);
}
 
Example 7
Source File: BookingIntegrationIT.java    From restful-booker-platform with GNU General Public License v3.0 5 votes vote down vote up
@Test
// We give the check a clear name to ensure that it is descriptive in
// what it is checking
public void testCreateBooking(){
    // We want to create a couple of date objects that we are going to us in our bookingPayload
    // and then again in the assertion to make sure they were processed correctly.
    LocalDate checkindate = LocalDate.of(1991, Month.JANUARY, 1);
    LocalDate checkoutdate = LocalDate.of(1991, Month.JANUARY, 2);

    // We next create our booking payload to send to the Booking webservice
    Booking bookingPayload = new Booking.BookingBuilder()
                                        .setRoomid(1)
                                        .setFirstname("Mark")
                                        .setLastname("Winteringham")
                                        .setDepositpaid(true)
                                        .setCheckin(checkindate)
                                        .setCheckout(checkoutdate)
                                        .setEmail("[email protected]")
                                        .setPhone("01928123456")
                                        .build();

    // We then send our request to the Booking webservice to create our booking
    Response bookingResponse = given()
                                .contentType(ContentType.JSON)
                                .body(bookingPayload)
                               .when()
                                .post("http://localhost:3000/booking/");

    System.out.println(bookingResponse.getBody().prettyPrint());

    // Once we get a response we extract the body and map it to CreatedBooking
    CreatedBooking response = bookingResponse.as(CreatedBooking.class);

    // Finally we assert on the various values we get from the HTTP response body
    assertThat(response.getBooking().getFirstname(), is("Mark"));
    assertThat(response.getBooking().getLastname(), is("Winteringham"));
    assertThat(response.getBooking().isDepositpaid(), is(true));
    assertThat(response.getBooking().getBookingDates().getCheckin(), is(checkindate));
    assertThat(response.getBooking().getBookingDates().getCheckout(), is(checkoutdate));
}
 
Example 8
Source File: LiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void accessCombinedEndpoint() {
    final Response response = RestAssured.given()
        .auth()
        .form("user", "password", formConfig)
        .get(ROOT_URI + "/combined?bookId=1");
    Assert.assertEquals(HttpStatus.OK.value(), response.getStatusCode());
    Assert.assertNotNull(response.getBody());
    final Book result = response.as(Book.class);
    Assert.assertEquals(new Long(1), result.getId());
    Assert.assertNotNull(result.getRatings());
    Assert.assertTrue(result.getRatings().size() > 0);
}
 
Example 9
Source File: ArtemisHealthCheckTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Response response = RestAssured.with().get("/health/ready");
    Assertions.assertEquals(Status.OK.getStatusCode(), response.statusCode());

    Map<String, Object> body = response.as(new TypeRef<Map<String, Object>>() {
    });
    Assertions.assertEquals("UP", body.get("status"));

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> checks = (List<Map<String, Object>>) body.get("checks");
    Assertions.assertEquals(1, checks.size());
    Assertions.assertEquals("Artemis Core health check", checks.get(0).get("name"));
}
 
Example 10
Source File: HibernateTenancyFunctionalityTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Fruit findByName(String tenantPath, String name) {
    Response response = given().config(config).when().get(tenantPath + "/fruitsFindBy?type=name&value={name}", name);
    if (response.getStatusCode() == Status.OK.getStatusCode()) {
        return response.as(Fruit.class);
    }
    return null;
}
 
Example 11
Source File: ArtemisHealthCheckTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Response response = RestAssured.with().get("/health/ready");
    Assertions.assertEquals(Status.OK.getStatusCode(), response.statusCode());

    Map<String, Object> body = response.as(new TypeRef<Map<String, Object>>() {
    });
    Assertions.assertEquals("UP", body.get("status"));

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> checks = (List<Map<String, Object>>) body.get("checks");
    Assertions.assertEquals(1, checks.size());
    Assertions.assertEquals("Artemis JMS health check", checks.get(0).get("name"));
}
 
Example 12
Source File: BdsqlSyncTest.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
private void cleanupBusinessData(User user, BusinessObjectData businessObjectData,
    boolean deleteNamespace) {
    String namespace = businessObjectData.getNamespace();
    String objectName = businessObjectData.getBusinessObjectDefinitionName();

    try {
        LogStep("Delete Business object data");
        Response response = HerdRestUtil.deleteBusinessObjectData(user, businessObjectData);
        BusinessObjectData responseBusinessObject = response.as(BusinessObjectData.class);

        LogStep("Delete business object notification registration");
        HerdRestUtil.deleteBusinessObjectNotification(user, namespace,
            namespace + "_" + objectName + "_OBJECT_MDL_USAGE_TXT");

        LogStep("Delete business object format registration");
        HerdRestUtil.deleteBusinessObjectFormat(user, businessObjectData);

        LogStep("Delete business object definition");
        HerdRestUtil.deleteBusinessObjectDefinition(user, namespace, objectName);

        if (deleteNamespace) {
            LogStep("Delete namespace");
            HerdRestUtil.deleteNamespace(user, namespace);
        }
    } catch (Exception e) {
        LOGGER.info("Failed on data cleanup, doesn't fail the testcase");
        LOGGER.warn(e.getMessage());
    }
}
 
Example 13
Source File: HerdRollingUpgradeTest.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches the current version of Herd running in the MDL stack
 *
 * @return String. Herd's build number
 */
private String getHerdBuildNumber() {

  // get buildInfo
  Response buildInfoResponse = HerdRestUtil.getBuildInfo(HERD_ADMIN_USER);

  // verify success
  Assert.assertEquals(HttpStatus.SC_OK, buildInfoResponse.getStatusCode());

  // Deserialize response
  BuildInformation buildInformation = buildInfoResponse
      .as(BuildInformation.class);

  return buildInformation.getBuildNumber();
}
 
Example 14
Source File: FruitsEndpointTest.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
private Fruit find(String tenantPrefix, String fruitName) {
    Response response = given().param("type", "name").param("value", fruitName).when().get(tenantPrefix + "/fruitsFindBy");
    if (response.statusCode() == 404) {
        return null;
    }
    if (response.statusCode() == 200) {
        Fruit fruit = response.as(Fruit.class);
        return fruit;
    }
    throw new IllegalStateException("Unknown status finding '" + fruitName + ": " + response);
}
 
Example 15
Source File: FruitsEndpointTest.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
private void deleteIfExist(String tenantPrefix, String fruitName) {
    Response response = given().param("type", "name").param("value", fruitName).when().get(tenantPrefix + "/fruitsFindBy");
    if (response.statusCode() == 200) {
        Fruit fruit = response.as(Fruit.class);
        given()
                .when().delete(tenantPrefix + "/fruits/" + fruit.getId())
                .then()
                .statusCode(204);
    }
}
 
Example 16
Source File: TokenSecuredResourceTest.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Test
@DisabledOnNativeImage("Doesn't work in the native mode due to a subresource issue")
public void testLottoWinners() {
    Response response = RestAssured.given().auth()
            .oauth2(token)
            .when()
            .get("/secured/lotto/winners").andReturn();

    Assertions.assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode());
    String replyString = response.body().asString();
    Json.createReader(new StringReader(replyString)).readObject();
    LottoNumbers numbers = response.as(LottoNumbers.class);
    Assertions.assertFalse(numbers.numbers.isEmpty());
}
 
Example 17
Source File: StreamingEndpointTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void testPipe() {
    Response r = get("/streaming/3");
    List<String> response = r.as(LIST_OF_STRING);
    assertThat(response).containsExactly("0", "0", "1", "3");
}
 
Example 18
Source File: MyUserLiveTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenGettingListOfUsers_thenCorrect() {
    final Response response = givenAuth().get(URL_PREFIX);
    final MyUser[] result = response.as(MyUser[].class);
    assertEquals(result.length, 2);
}
 
Example 19
Source File: MyUserLiveTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenPartialLastName_whenGettingListOfUsers_thenCorrect() {
    final Response response = givenAuth().get(URL_PREFIX + "?lastName=do");
    final MyUser[] result = response.as(MyUser[].class);
    assertEquals(result.length, 2);
}
 
Example 20
Source File: MyUserLiveTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenEmail_whenGettingListOfUsers_thenIgnored() {
    final Response response = givenAuth().get(URL_PREFIX + "?email=john");
    final MyUser[] result = response.as(MyUser[].class);
    assertEquals(result.length, 2);
}