3
respostas

Rest assured não faz parse do json

Estou tentando a horas fazer o teste da minha api rest e nada. Segui os passos e tentei executar o teste para retornar todos os produtos.

Erro apresentado quando executo o teste :

com.jayway.restassured.path.json.exception.JsonPathException: Failed to parse the JSON document

Se possivel me recomendem outra ferramenta para eu realizar os testes, se for fácil de configurar porque estou frustrado já.

    @Test
    public void deveBuscarTodosOsProdutos() {
        JsonPath path = given()
                .header("Accept", "application/json")
                .get("/todos")
                .andReturn()
                .jsonPath();

        Produto produto = path.getObject("produto", Produto.class);
        Produto esperado = new Produto("Cama Grande", TipoProduto.CAMA, 600, "Branca com listras", "Uma cama de 3m");

        Assert.assertEquals(esperado, produto);

    }
3 respostas

Posta o stack completo do erro, por favor

Troquei para o io Rest Assured a implementação está assim :

package Test;


import org.json.simple.JSONObject;
import org.junit.Assert;
import org.junit.Test;

import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class ProdutoResourceTestAssured{

    @Test
    public void deveBuscarTodosOsProdutos() {

        // Specify base URI
        RestAssured.baseURI = "http://localhost:8080/ProjetoJersey/api/produto";

        // Request Object
        RequestSpecification httpRequest = RestAssured.given();

        // Response Object
        Response response = httpRequest.request(Method.GET, "/todos");

        // Print response in console window
        String responseBody = response.getBody().asString();
        System.out.println("Response Body is: " + responseBody);

        // Status code validation
        int statusCode = response.getStatusCode();
        System.out.println("Status code is: " + statusCode);
        Assert.assertEquals(statusCode, 200);

        // Status line verification
        String statusLine = response.getStatusLine();
        System.out.println("Status line is: " + statusLine);
        Assert.assertEquals(statusLine, "HTTP/1.1 200 OK");

    }

    @SuppressWarnings("unchecked")
    @Test
    public void deveInserirUmProduto() {

        // Specify base URI
        RestAssured.baseURI = "http://localhost:8080/ProjetoJersey/api/produto";

        // Request Object
        RequestSpecification httpRequest = RestAssured.given();

        //Request playload sending along with post request
        JSONObject requestParams = new JSONObject();

        requestParams.put("nome", "MacBook PRO");
        requestParams.put("tipoProduto", "INFORMATICA");
        requestParams.put("valor", 26000.00);
        requestParams.put("cor", "Cinza Espacial");
        requestParams.put("especificacoes", "Top de linha");

        httpRequest.header("Content-type", "application/json");

        httpRequest.body(requestParams.toJSONString());

        // Response Object
        Response response = httpRequest.request(Method.POST, "/");

        // Print response in console window
        String responseBody = response.getBody().asString();
        System.out.println("Response Body is: " + responseBody);

        // Status code validation
        int statusCode = response.getStatusCode();
        System.out.println("Status code is: " + statusCode);
        Assert.assertEquals(statusCode, 201);

        // Success code validation
        String successCode = response.jsonPath().get("SuccessCode");
        Assert.assertEquals(successCode, "OPERATION_SUCCESS");

    }

}

Porém agora somente o post não funciona, diz que : Failed to Parse the JSON documente.

O campo onde está informatica é um enum na verdade, então se eu eu colocar :

requestParams.put("tipoProduto", TipoProduto.INFORMATICA);

E alterar o teste para esperar 400, eu recebo o seguinte: javax.ws.rs.ProcessingException: RESTEASY008200: JSON Binding deserialization error: Unexpected char 73 at (line no=1, column no=108, offset=107)

io.restassured.path.json.exception.JsonPathException: Failed to parse the JSON document
    at io.restassured.path.json.JsonPath$ExceptionCatcher.invoke(JsonPath.java:986)
    at io.restassured.path.json.JsonPath$4.doParseWith(JsonPath.java:951)
    at io.restassured.path.json.JsonPath$JsonParser.parseWith(JsonPath.java:1031)
    at io.restassured.path.json.JsonPath.get(JsonPath.java:202)
    at Test.ProdutoResourceTestAssured.deveInserirUmProduto(ProdutoResourceTestAssured.java:79)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.IllegalArgumentException: The JSON input text should neither be null nor empty.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:80)
    at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:105)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:235)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:247)
    at io.restassured.internal.path.json.ConfigurableJsonSlurper.parseText(ConfigurableJsonSlurper.groovy:80)
    at io.restassured.path.json.JsonPath$4$1.method(JsonPath.java:949)
    at io.restassured.path.json.JsonPath$ExceptionCatcher.invoke(JsonPath.java:984)
    ... 27 more