Hamcrest closeTo not working in RestAssured.body() Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceChecking that a List is not empty in Hamcrestjava.lang.NoClassDefFoundError: org/hamcrest/SelfDescribingHow to assertThat something is null with Hamcrest?Hamcrest compare collectionsDealing arrays with hamcrest and rest assuredClass not Found org/hamcrest/TypeSafeMatcherRestAssured check nested attribut inside an array attributeHamcrest exception message while actual and expected are sameHamcrest matchersMockMvc + Hamcrest: inconsistent collections for floating point numbers

3 doors, three guards, one stone

Is above average number of years spent on PhD considered a red flag in future academia or industry positions?

What was the last x86 CPU that did not have the x87 floating-point unit built in?

How does modal jazz use chord progressions?

Autumning in love

What did Darwin mean by 'squib' here?

Are my PIs rude or am I just being too sensitive?

The following signatures were invalid: EXPKEYSIG 1397BC53640DB551

Statistical model of ligand substitution

How do you clear the ApexPages.getMessages() collection in a test?

Slither Like a Snake

How to colour the US map with Yellow, Green, Red and Blue to minimize the number of states with the colour of Green

Is it possible to ask for a hotel room without minibar/extra services?

What do you call the holes in a flute?

Can a zero nonce be safely used with AES-GCM if the key is random and never used again?

Cold is to Refrigerator as warm is to?

Is there a documented rationale why the House Ways and Means chairman can demand tax info?

Unable to start mainnet node docker container

Keep going mode for require-package

Complexity of many constant time steps with occasional logarithmic steps

Can a monk deflect thrown melee weapons?

Passing functions in C++

Geometric mean and geometric standard deviation

Simulating Exploding Dice



Hamcrest closeTo not working in RestAssured.body()



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceChecking that a List is not empty in Hamcrestjava.lang.NoClassDefFoundError: org/hamcrest/SelfDescribingHow to assertThat something is null with Hamcrest?Hamcrest compare collectionsDealing arrays with hamcrest and rest assuredClass not Found org/hamcrest/TypeSafeMatcherRestAssured check nested attribut inside an array attributeHamcrest exception message while actual and expected are sameHamcrest matchersMockMvc + Hamcrest: inconsistent collections for floating point numbers



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have a test that I cannot get the syntax correctly:



@Test
void statsTest()
given().queryParam("param", "ball")
.when().get()
.then().body("total", is(closeTo(10.0, 0.1*10.0))));



However, the test keeps failing even though the condition is met:



java.lang.AssertionError: 1 expectation failed.
JSON path total doesn't match.
Expected: is a numeric value within <1.0> of <10.0>
Actual: 10


I've never had a problem with types before in this setup of RestAssured and Hamcrest. For example, a test of the sort: body("total", greaterThan(9)) works fine, which means that there is some type casting under the hood.



I've looked through the docs and cannot find a way to cast the value of body("total") to a numerical value.
so I suspect that this is a bug or I'm not understanding something here.



Here's the JSON response. I had to clip it to make is short. Hope this works.




"stats":
"totalHits": 1,
"searchEngineTimeInMillis": 83,
"searchEngineRoundTripTimeInMillis": 87,
"searchProcessingTimeInMillis": 101
,
"products":
"id": "total",
"displayName": "Documents",
"ball": 10










share|improve this question



















  • 1





    Please post your JSON response and I can try simulating

    – Wilfred Clement
    Mar 8 at 15:14












  • @WilfredClement I've added the JSON response, a trimmed version. Let me know you have problems with it.

    – Shejo284
    Mar 8 at 15:31






  • 1





    Possibly the value of total in response JSON is integer where are comparison is being made to float?

    – SudhirR
    Mar 8 at 17:09











  • @SudhirR ok. Any idea how to cast the response to a double?

    – Shejo284
    Mar 8 at 18:34






  • 1





    @Shejo284 instead of comparing with a float range, why don't you compare to an int range. .then().body("total", allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)));

    – SudhirR
    Mar 9 at 11:50

















0















I have a test that I cannot get the syntax correctly:



@Test
void statsTest()
given().queryParam("param", "ball")
.when().get()
.then().body("total", is(closeTo(10.0, 0.1*10.0))));



However, the test keeps failing even though the condition is met:



java.lang.AssertionError: 1 expectation failed.
JSON path total doesn't match.
Expected: is a numeric value within <1.0> of <10.0>
Actual: 10


I've never had a problem with types before in this setup of RestAssured and Hamcrest. For example, a test of the sort: body("total", greaterThan(9)) works fine, which means that there is some type casting under the hood.



I've looked through the docs and cannot find a way to cast the value of body("total") to a numerical value.
so I suspect that this is a bug or I'm not understanding something here.



Here's the JSON response. I had to clip it to make is short. Hope this works.




"stats":
"totalHits": 1,
"searchEngineTimeInMillis": 83,
"searchEngineRoundTripTimeInMillis": 87,
"searchProcessingTimeInMillis": 101
,
"products":
"id": "total",
"displayName": "Documents",
"ball": 10










share|improve this question



















  • 1





    Please post your JSON response and I can try simulating

    – Wilfred Clement
    Mar 8 at 15:14












  • @WilfredClement I've added the JSON response, a trimmed version. Let me know you have problems with it.

    – Shejo284
    Mar 8 at 15:31






  • 1





    Possibly the value of total in response JSON is integer where are comparison is being made to float?

    – SudhirR
    Mar 8 at 17:09











  • @SudhirR ok. Any idea how to cast the response to a double?

    – Shejo284
    Mar 8 at 18:34






  • 1





    @Shejo284 instead of comparing with a float range, why don't you compare to an int range. .then().body("total", allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)));

    – SudhirR
    Mar 9 at 11:50













0












0








0








I have a test that I cannot get the syntax correctly:



@Test
void statsTest()
given().queryParam("param", "ball")
.when().get()
.then().body("total", is(closeTo(10.0, 0.1*10.0))));



However, the test keeps failing even though the condition is met:



java.lang.AssertionError: 1 expectation failed.
JSON path total doesn't match.
Expected: is a numeric value within <1.0> of <10.0>
Actual: 10


I've never had a problem with types before in this setup of RestAssured and Hamcrest. For example, a test of the sort: body("total", greaterThan(9)) works fine, which means that there is some type casting under the hood.



I've looked through the docs and cannot find a way to cast the value of body("total") to a numerical value.
so I suspect that this is a bug or I'm not understanding something here.



Here's the JSON response. I had to clip it to make is short. Hope this works.




"stats":
"totalHits": 1,
"searchEngineTimeInMillis": 83,
"searchEngineRoundTripTimeInMillis": 87,
"searchProcessingTimeInMillis": 101
,
"products":
"id": "total",
"displayName": "Documents",
"ball": 10










share|improve this question
















I have a test that I cannot get the syntax correctly:



@Test
void statsTest()
given().queryParam("param", "ball")
.when().get()
.then().body("total", is(closeTo(10.0, 0.1*10.0))));



However, the test keeps failing even though the condition is met:



java.lang.AssertionError: 1 expectation failed.
JSON path total doesn't match.
Expected: is a numeric value within <1.0> of <10.0>
Actual: 10


I've never had a problem with types before in this setup of RestAssured and Hamcrest. For example, a test of the sort: body("total", greaterThan(9)) works fine, which means that there is some type casting under the hood.



I've looked through the docs and cannot find a way to cast the value of body("total") to a numerical value.
so I suspect that this is a bug or I'm not understanding something here.



Here's the JSON response. I had to clip it to make is short. Hope this works.




"stats":
"totalHits": 1,
"searchEngineTimeInMillis": 83,
"searchEngineRoundTripTimeInMillis": 87,
"searchProcessingTimeInMillis": 101
,
"products":
"id": "total",
"displayName": "Documents",
"ball": 10







groovy rest-assured hamcrest rest-assured-jsonpath






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 16:07







Shejo284

















asked Mar 8 at 14:58









Shejo284Shejo284

1,40221831




1,40221831







  • 1





    Please post your JSON response and I can try simulating

    – Wilfred Clement
    Mar 8 at 15:14












  • @WilfredClement I've added the JSON response, a trimmed version. Let me know you have problems with it.

    – Shejo284
    Mar 8 at 15:31






  • 1





    Possibly the value of total in response JSON is integer where are comparison is being made to float?

    – SudhirR
    Mar 8 at 17:09











  • @SudhirR ok. Any idea how to cast the response to a double?

    – Shejo284
    Mar 8 at 18:34






  • 1





    @Shejo284 instead of comparing with a float range, why don't you compare to an int range. .then().body("total", allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)));

    – SudhirR
    Mar 9 at 11:50












  • 1





    Please post your JSON response and I can try simulating

    – Wilfred Clement
    Mar 8 at 15:14












  • @WilfredClement I've added the JSON response, a trimmed version. Let me know you have problems with it.

    – Shejo284
    Mar 8 at 15:31






  • 1





    Possibly the value of total in response JSON is integer where are comparison is being made to float?

    – SudhirR
    Mar 8 at 17:09











  • @SudhirR ok. Any idea how to cast the response to a double?

    – Shejo284
    Mar 8 at 18:34






  • 1





    @Shejo284 instead of comparing with a float range, why don't you compare to an int range. .then().body("total", allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)));

    – SudhirR
    Mar 9 at 11:50







1




1





Please post your JSON response and I can try simulating

– Wilfred Clement
Mar 8 at 15:14






Please post your JSON response and I can try simulating

– Wilfred Clement
Mar 8 at 15:14














@WilfredClement I've added the JSON response, a trimmed version. Let me know you have problems with it.

– Shejo284
Mar 8 at 15:31





@WilfredClement I've added the JSON response, a trimmed version. Let me know you have problems with it.

– Shejo284
Mar 8 at 15:31




1




1





Possibly the value of total in response JSON is integer where are comparison is being made to float?

– SudhirR
Mar 8 at 17:09





Possibly the value of total in response JSON is integer where are comparison is being made to float?

– SudhirR
Mar 8 at 17:09













@SudhirR ok. Any idea how to cast the response to a double?

– Shejo284
Mar 8 at 18:34





@SudhirR ok. Any idea how to cast the response to a double?

– Shejo284
Mar 8 at 18:34




1




1





@Shejo284 instead of comparing with a float range, why don't you compare to an int range. .then().body("total", allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)));

– SudhirR
Mar 9 at 11:50





@Shejo284 instead of comparing with a float range, why don't you compare to an int range. .then().body("total", allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)));

– SudhirR
Mar 9 at 11:50












2 Answers
2






active

oldest

votes


















1














The key value pair corresponding to key: "total" in your response seems to be of integer type. So it needs to be checked for bounds with integer based bounds (1,10). So instead of using the closeTo matcher, you can use the following matcher.



allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)))





share|improve this answer























  • Thanks for the code. This thought was to check the bounds on both sides of the 10, so I need to also check the range [10, 20]. Check out my solution above :-)

    – Shejo284
    Mar 11 at 6:00


















1














I've put together another approach that solves the problem but with a slightly different approach. Much thanks to those who populate the web with their code samples. The following assumes you already have set the base URI and PATH. You can add a path deeper in the response by using the get("/path..."). This answer assumes a JSON type response.



 private static Response getResponse(String paramName, String paramValue) 
return given().queryParam(paramName, paramValue)
.when().get();


public static String getJsonValue(String jsonPath, String paramName, String paramValue)
Response response = getResponse(paramName, paramValue);
//response.getBody().prettyPrint();
JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get(jsonPath).toString();



You can simply print the return value and cast it to the type you need.
The test then looks like this:



 public static void checkIfNumberCloseToValue(String jsonPath,
String paramName,
String paramValue,
Double error,
Double expected)
Double value = Double.valueOf(Utils.getJsonValue(jsonPath, paramName, paramValue));
double range = expected * error;
assertThat(value, closeTo(expected, range));






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55065814%2fhamcrest-closeto-not-working-in-restassured-body%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    The key value pair corresponding to key: "total" in your response seems to be of integer type. So it needs to be checked for bounds with integer based bounds (1,10). So instead of using the closeTo matcher, you can use the following matcher.



    allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)))





    share|improve this answer























    • Thanks for the code. This thought was to check the bounds on both sides of the 10, so I need to also check the range [10, 20]. Check out my solution above :-)

      – Shejo284
      Mar 11 at 6:00















    1














    The key value pair corresponding to key: "total" in your response seems to be of integer type. So it needs to be checked for bounds with integer based bounds (1,10). So instead of using the closeTo matcher, you can use the following matcher.



    allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)))





    share|improve this answer























    • Thanks for the code. This thought was to check the bounds on both sides of the 10, so I need to also check the range [10, 20]. Check out my solution above :-)

      – Shejo284
      Mar 11 at 6:00













    1












    1








    1







    The key value pair corresponding to key: "total" in your response seems to be of integer type. So it needs to be checked for bounds with integer based bounds (1,10). So instead of using the closeTo matcher, you can use the following matcher.



    allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)))





    share|improve this answer













    The key value pair corresponding to key: "total" in your response seems to be of integer type. So it needs to be checked for bounds with integer based bounds (1,10). So instead of using the closeTo matcher, you can use the following matcher.



    allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(10)))






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 11 at 5:37









    SudhirRSudhirR

    373110




    373110












    • Thanks for the code. This thought was to check the bounds on both sides of the 10, so I need to also check the range [10, 20]. Check out my solution above :-)

      – Shejo284
      Mar 11 at 6:00

















    • Thanks for the code. This thought was to check the bounds on both sides of the 10, so I need to also check the range [10, 20]. Check out my solution above :-)

      – Shejo284
      Mar 11 at 6:00
















    Thanks for the code. This thought was to check the bounds on both sides of the 10, so I need to also check the range [10, 20]. Check out my solution above :-)

    – Shejo284
    Mar 11 at 6:00





    Thanks for the code. This thought was to check the bounds on both sides of the 10, so I need to also check the range [10, 20]. Check out my solution above :-)

    – Shejo284
    Mar 11 at 6:00













    1














    I've put together another approach that solves the problem but with a slightly different approach. Much thanks to those who populate the web with their code samples. The following assumes you already have set the base URI and PATH. You can add a path deeper in the response by using the get("/path..."). This answer assumes a JSON type response.



     private static Response getResponse(String paramName, String paramValue) 
    return given().queryParam(paramName, paramValue)
    .when().get();


    public static String getJsonValue(String jsonPath, String paramName, String paramValue)
    Response response = getResponse(paramName, paramValue);
    //response.getBody().prettyPrint();
    JsonPath jsonPathEvaluator = response.jsonPath();
    return jsonPathEvaluator.get(jsonPath).toString();



    You can simply print the return value and cast it to the type you need.
    The test then looks like this:



     public static void checkIfNumberCloseToValue(String jsonPath,
    String paramName,
    String paramValue,
    Double error,
    Double expected)
    Double value = Double.valueOf(Utils.getJsonValue(jsonPath, paramName, paramValue));
    double range = expected * error;
    assertThat(value, closeTo(expected, range));






    share|improve this answer



























      1














      I've put together another approach that solves the problem but with a slightly different approach. Much thanks to those who populate the web with their code samples. The following assumes you already have set the base URI and PATH. You can add a path deeper in the response by using the get("/path..."). This answer assumes a JSON type response.



       private static Response getResponse(String paramName, String paramValue) 
      return given().queryParam(paramName, paramValue)
      .when().get();


      public static String getJsonValue(String jsonPath, String paramName, String paramValue)
      Response response = getResponse(paramName, paramValue);
      //response.getBody().prettyPrint();
      JsonPath jsonPathEvaluator = response.jsonPath();
      return jsonPathEvaluator.get(jsonPath).toString();



      You can simply print the return value and cast it to the type you need.
      The test then looks like this:



       public static void checkIfNumberCloseToValue(String jsonPath,
      String paramName,
      String paramValue,
      Double error,
      Double expected)
      Double value = Double.valueOf(Utils.getJsonValue(jsonPath, paramName, paramValue));
      double range = expected * error;
      assertThat(value, closeTo(expected, range));






      share|improve this answer

























        1












        1








        1







        I've put together another approach that solves the problem but with a slightly different approach. Much thanks to those who populate the web with their code samples. The following assumes you already have set the base URI and PATH. You can add a path deeper in the response by using the get("/path..."). This answer assumes a JSON type response.



         private static Response getResponse(String paramName, String paramValue) 
        return given().queryParam(paramName, paramValue)
        .when().get();


        public static String getJsonValue(String jsonPath, String paramName, String paramValue)
        Response response = getResponse(paramName, paramValue);
        //response.getBody().prettyPrint();
        JsonPath jsonPathEvaluator = response.jsonPath();
        return jsonPathEvaluator.get(jsonPath).toString();



        You can simply print the return value and cast it to the type you need.
        The test then looks like this:



         public static void checkIfNumberCloseToValue(String jsonPath,
        String paramName,
        String paramValue,
        Double error,
        Double expected)
        Double value = Double.valueOf(Utils.getJsonValue(jsonPath, paramName, paramValue));
        double range = expected * error;
        assertThat(value, closeTo(expected, range));






        share|improve this answer













        I've put together another approach that solves the problem but with a slightly different approach. Much thanks to those who populate the web with their code samples. The following assumes you already have set the base URI and PATH. You can add a path deeper in the response by using the get("/path..."). This answer assumes a JSON type response.



         private static Response getResponse(String paramName, String paramValue) 
        return given().queryParam(paramName, paramValue)
        .when().get();


        public static String getJsonValue(String jsonPath, String paramName, String paramValue)
        Response response = getResponse(paramName, paramValue);
        //response.getBody().prettyPrint();
        JsonPath jsonPathEvaluator = response.jsonPath();
        return jsonPathEvaluator.get(jsonPath).toString();



        You can simply print the return value and cast it to the type you need.
        The test then looks like this:



         public static void checkIfNumberCloseToValue(String jsonPath,
        String paramName,
        String paramValue,
        Double error,
        Double expected)
        Double value = Double.valueOf(Utils.getJsonValue(jsonPath, paramName, paramValue));
        double range = expected * error;
        assertThat(value, closeTo(expected, range));







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 11 at 5:57









        Shejo284Shejo284

        1,40221831




        1,40221831



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55065814%2fhamcrest-closeto-not-working-in-restassured-body%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved