EzDevInfo.com

rest-assured

Java DSL for easy testing of REST services

Spring Mock mvc rest-assured test fails to get status

Getting error while trying to test while running RestAssuredMockMvc and Spring:

INFO - Mapped "{[/mysql/hello],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String ee.t.mysql.controllers.testController.printHello()
INFO - HV000001: Hibernate Validator 5.1.2.Final
INFO - Looking for @ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext@4d7cca20
INFO - Initializing Spring FrameworkServlet ''
INFO - FrameworkServlet '': initialization started
INFO - FrameworkServlet '': initialization completed in 6 ms

java.lang.NoSuchMethodError: javax.servlet.http.HttpServletResponse.getStatus()I
    at org.springframework.web.servlet.FrameworkServlet.publishRequestHandledEvent(FrameworkServlet.java:1066)

UPDATE:

fixed by changing version to 3.x:

 <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

Source: (StackOverflow)

Empty respond body for post with rest assured

I am using restassured with junit4. In my test method i create a object in mongodb and when i run the test it successfully persist also. But i need to store the id created so i try to get the respond body. But the response.getBody().asString() is empty.

@Test
public void testA() throws JSONException {

    Map<String,Object> createVideoAssignmentParm = new HashMap<String,Object>();
    createVideoAssignmentParm.put("test1", "123");

    Response response = expect().statusCode(201).when().given().contentType("application/json;charset=UTF-8")
            .headers(createVideoAssignmentParm).body(assignment).post("videoAssignments");
    JSONObject jsonObject = new JSONObject(response.getBody().asString());
    id= (String)jsonObject.getString("assignmentId");
}

When i invoke the rest end point externally, it returns the response body also with relevant fields so no problem with the rest API.

If no answer for above question then how would you guys test a post with return body using rest assured so that i can try that way.

My controller method looks like,

 @RequestMapping(value = "/videoAssignment", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE, method = RequestMethod.POST)
 @ResponseBody
 public HttpEntity<VideoAssignment> createVideoAssingnment(
  //@ApiParam are there..){

    //other methods
    return new ResponseEntity<>(va, HttpStatus.CREATED);
 }

Source: (StackOverflow)

Advertisements

Rest Assured - can't POST with Parameters and Body

I'm testing a REST api using Rest Assured. I'm running into an error when trying to POST with both a parameter in the url and body content. This works correctly when testing manually. Removing the parameter form the url is not an option

Test Code:

String endpoint = http://localhost:8080/x/y/z/id?custom=test;
String body = "[{\"boolField\":true,\"intField\":991},
                {\"boolField\":false,\"intField\":998}]";
expect().spec(OK).given().body(body).post(endpoint);

Which throws the following error when run

You can either send parameters OR body content in the POST, not both!

java.lang.IllegalStateException: You can either send parameters OR body content in the POST, not both!
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:102)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:198)
at com.jayway.restassured.internal.RequestSpecificationImpl.sendRequest(RequestSpecificationImpl.groovy:282)
at com.jayway.restassured.internal.RequestSpecificationImpl.this$2$sendRequest(RequestSpecificationImpl.groovy)
at com.jayway.restassured.internal.RequestSpecificationImpl$this$2$sendRequest.callCurrent(Unknown Source)
at com.jayway.restassured.internal.RequestSpecificationImpl.post(RequestSpecificationImpl.groovy:83)
...

Why does Rest Assured not allow both parameters and body content in a POST?


Source: (StackOverflow)

Deserialize json array and extract value using rest assured

I am a java, json, rest assured newbie and trying to work and learn how to test a rest api. I have an array returned as a rest assured response:

 Response response = given(getProjectInfoRequest).get();
 response.asString(); 

{
    "options": [
        {
            "text": "111",
            "label": "ABC"
        },
        {
            "text": "222",
            "label": "DEF"
        },
        {
            "text": "333",
            "label": "GHI"
        }
    ]
}

and I want to extract the value of text say for label value as "DEF", how I can do that?

Please note I have done below so far after reading through so many posts:

1. Options[] options = given(getProjectInfoRequest).when().get().as(Options[].class);
this was giving me exception :
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

then I tried below:
2. Options options = gson.fromJson(response.asString(), Options.getClass());
this at least resolved the above issue.
    public class Options {
    public String getLabel() {
        return label
    }

    public void setLabel(String label) {
        this.label = label
    }

    public String getValue() {
        return value
    }

    public void setValue(String value) {
        this.value = value
    }
    public String label;
    public String value;
} 

From this point I am not sure how I can iterate through the array of text and values to extract what I need, please can you guys provide your inputs?

Please pardon my ignorance for asking such a basic question. Please also suggest me a good source/way to learn this too.

Thanks in advance!


Source: (StackOverflow)

Rest-assured requests not working

I am using Rest-Assured to test my Rest API. the webservice seems to be running ok, since running

    curl -u "admin:admin" http://localhost:8888/users/

i get my Users as json.

then, when trying a simple request with Rest-Assured

 RestAssured.authentication = basic("admin", "admin");

  expect().statusCode(200).when().get("http://localhost:8888/users/");

gives me the output

    Exception in thread "main" org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8888 refused
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:158)
…

what can this be?


Source: (StackOverflow)

RestAssured content-type application/json not being recognised by service

I have a service, which I can access with the following jQuery code (from google chrome with --disable-web-security)

$.ajax({
    type: 'POST',
    url: "http://10.30.1.2:9234/myapp/v6/token/generate",
    headers: {
        "Content-Type":"application/json",
        "Accept":"application/json"
    },
    data: JSON.stringify({ 
      "staffId" : "13254",
      "password" : "JustADummyPassword"
    })
}).done(function(data) { 
    console.log(data);
});

$.ajax({
    type: 'GET',
    url: "http://10.30.1.2:9234/myapp/v6/user/appl/Firstname/Lastname/email@address.com/1998-01-01",
    headers: {
        "Content-Type":"application/json",
        "Accept":"application/json"
    }
}).done(function(data) { 
    console.log(data);
});

The first call sets a cookie, which is required for the second call to authenticate. This works fine, and both requests return expected results.

I am trying to set up automated testing for the service, and have this written in JAVA, using RestAssured.

public class UserApplication {
    public static Map<String, String> authCookies = null;
    public static String JSESSIONID = null;
    public static void main(String[] args) {
        Response resp = hello();
        resp = apiUserApplication();
    }

    public static Response apiUserApplication() {
        String userAppl = "http://10.30.1.2:9234/myapp/v6/user/appl/Firstname/Lastname/email@address.com/1998-01-01";

        Response response = RestAssured.given()
                .cookie("JSESSIONID", JSESSIONID).and()
                .header("Accept", "application/json").and()
                .header("Content-Type", "application/json").and()
                .when().get(userAppl);

        return response;
    }

    public static Response hello() {
        String helloUrl = "http://10.30.1.2:9234/myapp/v6/hello";

        Response response = RestAssured.given().cookies(authCookies)
                .contentType("application/json").when().get(helloUrl);

        return response;
    }
}

The first call (hello) works fine, and returns 200 code, and gets a valid token for use in the second call. The error I am getting from the second call with a 400 status code is...

{"errors":["Content type 'null' not supported"]}

Source: (StackOverflow)

running integration tests in teamcity using spring-boot and restassured

I am writing my integration tests using springboot and rest-assured and using SpringApplicationConfiguration to load the configuration.

This is what the test class annotation look like:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = RestAPIApplication.class)
@IntegrationTest("server.port:8083") // this is the port set by my application 

Now comes my real question. When I run the test class in teamcity using maven, don't I have to configure something to run the springboot server before running the integration tests?

I am new to springboot so maybe this question is very novice but please point me to the correct path.


Source: (StackOverflow)

Access elements of an anonymous array in JsonPath in Rest-assured

I have an anonymous array in JSON returned from a service like (pseudo code):

[
  {foo:1, bar:2 , baz:3 },
  {foo:3, bar:4 , baz:5 }
]

How can I access the bar elements e.g. in

expect().body("$[*].bar",hasItems(2,4)) 

I tried a few possibilities that I found here and also on the JsonPath page by Stefan Gössner, but whatever I try I get exceptions. My issue seems to directly come from trying to access that list of items.


Source: (StackOverflow)

REST Assured - Generic List deserialization

Let's say I have a Java Person class:

class Person {
    String name;
    String email;
}

With REST Assured, you can deserialize this JSON object

{"name":"Bob", "email":"bob@email.com"} 

to a Java Person instance using

Person bob = given().when().get("person/Bob/").as(Person.class);

How does one use REST Assured to deserialize this JSON array

[{"name":"Bob", "email":"bob@email.com"}, 
 {"name":"Alice", "email":"alice@email.com"}, 
 {"name":"Jay", "email":"jay@email.com"}]

into a List<Person>? For example, this would be handy:

List<Person> persons = given().when().get("person/").as(...);

Source: (StackOverflow)

How to use REST assured?

I have never used JUnit or other testing frameworks. All i know is how to develop rest service. I recently saw REST assured framework to test REST api. But all the articles that i found looks like below. But i don't know how to pass request xml and how will i get response and when should i call this method.?

Do i need to use some other tool before this REST assured.? I am completely beginner in this kind of testing frameworks. Please show me some light in this world. All i know is how to send request and check values in the response in SOAPUI. I have never tried this.

expect().
    statusCode(200).
    body(
      "user.email", equalTo("test@hascode.com"),
      "user.firstName", equalTo("Tim"),
      "user.lastName", equalTo("Testerman"),
      "user.id", equalTo("1")).
    when().
    get("/service/single-user/xml");

Source: (StackOverflow)

how to handle upload a file in rest assured API testing?

how to handle upload a file in rest assured API testing ?

like u have to use post(/url) and then upload a file at specific paramater.?


Source: (StackOverflow)

Rest Assured Exception when test fails

I have a simple rest-assured test that is verifying this json comes be with the correct data for a call. I am using rest-assured 1.8 and did swap the groovy jars for the groovy-all jar due to a known issue with 2 different versions of ASM.

My json the comes back looks like this: {"account":"12345"}

My code looks like this:

package com.blah.tests;

import org.junit.Test;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class AccountsTest {

public AccountsTest() {
}


@Test
public void getLocationAccount() {

            given().
                param("thingAccountIsfor","ABCD").
            expect().
                statusCode(200).
                body("account",equalTo("10")).
            when().
                get("http://machine:2343/rest/accounts/getaccount");

    }

}

When I run this matching the value i expect for the account it works fine. When I put in a value that does not match I get a stack trace:

log4j:WARN No appenders could be found for logger (org.apache.http.impl.conn.SingleClientConnManager). log4j:WARN Please initialize the log4j system properly.

java.lang.AssertionError: 1 expectation failed. JSON path account doesn't match. Expected: 10 Actual: 12345

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:71)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:81)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:57)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:182)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:190)
at com.jayway.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:399)
at com.jayway.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at com.jayway.restassured.internal.RequestSpecificationImpl.invokeFilterChain(RequestSpecificationImpl.groovy:759)
at com.jayway.restassured.internal.RequestSpecificationImpl$invokeFilterChain.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:149)
at com.jayway.restassured.internal.RequestSpecificationImpl.applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy:1142)
at com.jayway.restassured.internal.RequestSpecificationImpl.this$2$applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy)
at com.jayway.restassured.internal.RequestSpecificationImpl$this$2$applyPathParamsAndSendRequest.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:149)
at com.jayway.restassured.internal.RequestSpecificationImpl.get(RequestSpecificationImpl.groovy:131)
at com.jayway.restassured.specification.RequestSender$get.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at com.jayway.restassured.internal.ResponseSpecificationImpl.get(ResponseSpecificationImpl.groovy:226)
at com.tim.tests.AccountsTest.getLocationAccount(AccountsTest.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:77)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:195)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Process finished with exit code 255

I am running this inside Intellij. I did try to move the groovy jars, back in, move the conflicting version of the ASM off of my class path and re-run it. I got the same result so I don't beleive this has to do with using the groovy-all jar instead of the groovy jars that ship with rest-assured 1.8.

Does rest-assured throw an exception every time it has a test fail or is something wrong here?


Source: (StackOverflow)

REST Assured and multiple posts

I'm trying to use REST assured to test my login/logout feature. Is it possible to have a REST assured test that posts to login then posts to logout? If not, how can I test it properly?


Source: (StackOverflow)

Configuring redirect strategy

I'm testing an endpoint that returns a Location header with spaces ( it can't be fixed ) and I receive org.apache.http.ClientProtocolException. According to other answers, I have to create RedirectStrategy and encode spaces with %20.

Looking through the documentation I found a small section about HTTP Client config but it seems it contains only basic info.

How can I set RedirectStrategy to RestAssured to encode spaces in the Location header with %20 ?


Source: (StackOverflow)

Assert alternative (or)

I have an endpoint which returns either true or false. Is it somehow possible to tell Hamcrest with RestAssured to check whether there exist one of mentioned two ? I've already tried containsString, hasItems etc, but none of them works i.e it checks for both of them.

get("http://localhost:8080/trueOrFalse")
        .then()
        .body(hasItems("true", "false")); // TRUE or FALSE not both 

Source: (StackOverflow)