How do I convert a JSONObject to JSON?

162 views Asked by At

I Have want the verify a body containing a JSON. I use a JSONObject the expected value.

package com.steinko.todo;

import com.steinko.reactsprinboottutorial.RestfulWebService.HelloWorldController;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Disabled;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.springframework.http.HttpStatus.OK;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
 
import  org.json.simple.JSONObject;


class HelloWorldControllerTest {
    
    HelloWorldController controller = new HelloWorldController();
    


    @Test
    void shouldGetHelloWorldMessage() {
        
        JSONObject expected =new JSONObject();    
          expected.put("message","Hello World Bean");       
           
        given()
          .standaloneSetup(controller)
        .when()
          .get("/hello-world-bean")
        .then()
          .statusCode(OK.value())
          .body(is(equalTo(expected)));  
    }   
 }  

When I run this test I get following error message

java.lang.AssertionError: 1 expectation failed. Response body doesn't match expectation. Expected: is <{"message":"Hello World Bean"}> Actual: {"message":"Hello World Bean"}

How do I convert the JSONObject to Json format?

1

There are 1 answers

0
SimGel On

You have to convert the json object to its string repesentation.

expected.toString()

In your case:

.body(is(equalTo(expected.toString()));