3
respostas

Como faço para testar a lista de leilões usando Json?

Como faço para testar a lista de leilões usando Json?

Como o código abaixo dá o seguinte erro: java.lang.ClassCastException: Cannot convert class java.util.HashMap to class br.com.caelum.leilao.modelo.Leilao.

@Test
    public void deveRetornarListaDeLeiloesJson() {
        JsonPath path = given()
                .header("Accept", "application/json")
                .get("/leiloes")
                .andReturn().jsonPath();
        List<Leilao> leiloes = path.getList("list", Leilao.class);

        assertEquals(leilaoEsperado1, leiloes.get(0));
        assertEquals(leilaoEsperado2, leiloes.get(1));
    }

O Json retornado por "/leiloes" é o seguinte:

{"list": [{"id": 1,"nome": "Geladeira","valorInicial": 800.0,"usuario": {"id": 1,"nome": "Mauricio Aniche","email": "mauricio.aniche@caelum.com.br"},"usado": false},{"id": 2,"nome": "XBox","valorInicial": 450.0,"usuario": {"id": 2,"nome": "Guilherme Silveira","email": "guilherme.silveira@caelum.com.br"},"usado": false}]}
3 respostas

Oi Marcos,

Qual versão do Rest Assured você está utilizando? Parece que este problema só foi corrigido na versão 2.9.1: https://groups.google.com/forum/m/#!topic/rest-assured/wqFfQM0Ag44

Abraço!

Mudei para a versão 3.0.1 e funcionou com o seguinte código:

package br.com.caelum.leilao.teste;

import static io.restassured.RestAssured.given;
import static org.junit.Assert.assertEquals;
import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

import br.com.caelum.leilao.modelo.Leilao;
import br.com.caelum.leilao.modelo.Usuario;

public class LeilaoWSTest {

    private Usuario mauricio;
    private Usuario guilherme;
    private Leilao geladeira;
    private Leilao xbox;
    private Leilao notebook;

    @Before
    public void setUp(){
        mauricio = new Usuario(1L, "Mauricio Aniche", "mauricio.aniche@caelum.com.br");
        geladeira = new Leilao(1l, "Geladeira", 800.0, mauricio, false);
        guilherme = new Usuario(2L, "Guilherme Silveira", "guilherme.silveira@caelum.com.br");
        xbox = new Leilao(2l, "XBox", 450.0, guilherme, false);
        notebook = new Leilao(3L, "Notebook", 2000.0, mauricio, false);
    }

    @Test
    public void deveRetornarListaDeLeiloes() {
        XmlPath path = given().
                header("Accept", "application/xml")
                .get("/leiloes")
                .andReturn().xmlPath();

        List<Leilao> leiloes = path.getList("list.leilao", Leilao.class);

        assertEquals(geladeira, leiloes.get(0));
        assertEquals(xbox, leiloes.get(1));
    }

    @Test
    public void deveRetornarListaDeLeiloesJson() {
        JsonPath path = given()
                .header("Accept", "application/json")
                .get("/leiloes")
                .andReturn().jsonPath();
        List<Leilao> leiloes = path.getList("list", Leilao.class);

        assertEquals(geladeira, leiloes.get(0));
        assertEquals(xbox, leiloes.get(1));
    }

    @Test
    public void deveRetornarLeilaoPorIdJson() {
        JsonPath path = given()
                .header("Accept", "application/json")
                .param("leilao.id", 1)
                .get("/leiloes/show")
                .andReturn().jsonPath();

        Leilao leilaoEsperado = path.getObject("leilao", Leilao.class);
        assertEquals(geladeira, leilaoEsperado);

    }

    @Test
    public void deveRetornarTotalDeLeiloes() {
        XmlPath path = given().
                header("Accept", "application/xml")
                .get("/leiloes/total")
                .andReturn().xmlPath();

        int total = path.getInt("");

        assertEquals(2, total);
    }

    @Test
    public void deveAdicionarUmLeilao() {
        XmlPath xpath = 
            given()
                .header("Accept", "application/xml")
                .contentType("application/xml")
                .body(notebook)
            .expect()
                .statusCode(200)
            .when()
                .post("/leiloes")
            .andReturn()
                .xmlPath();

        Leilao resposta = xpath.getObject("leilao", Leilao.class);
        assertEquals(notebook.getNome(), resposta.getNome());
        assertEquals(notebook.getValorInicial(), resposta.getValorInicial());
        assertEquals(notebook.getUsuario(), resposta.getUsuario());

        given()
            .contentType("application/xml")
            .body(resposta)
        .expect()
            .statusCode(200)
        .when()
            .delete("/leiloes/deletar")
        .andReturn()
            .asString();
    }
}

Porém, percebi um outro problema no teste de Usuários. Aparentemente o serviço não deleta um usuário. O código que usei foi esse:

package br.com.caelum.leilao.teste;

import static io.restassured.RestAssured.given;
import static org.junit.Assert.assertEquals;
import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

import br.com.caelum.leilao.modelo.Usuario;

public class UsuariosWSTest {

    private Usuario mauricio;
    private Usuario guilherme;
    private Usuario joao;

    @Before
    public void setUp(){
        mauricio = new Usuario(1L, "Mauricio Aniche", "mauricio.aniche@caelum.com.br");
        guilherme = new Usuario(2L, "Guilherme Silveira", "guilherme.silveira@caelum.com.br");
        joao = new Usuario(3L, "Joao da Silva", "joao@dasilva.com");
    }

    @Test
    public void deveRetornarListaDeUsuarios() {
        XmlPath path = given().
                header("Accept", "application/xml")
                .get("/usuarios")
                .andReturn().xmlPath();

        List<Usuario> usuarios = path.getList("list.usuario", Usuario.class);

        assertEquals(mauricio, usuarios.get(0));
        assertEquals(guilherme, usuarios.get(1));
    }

    @Test
    public void deveRetornarListaDeUsuariosJson() {
        JsonPath path = given()
                .header("Accept", "application/json")
                .get("/usuarios")
                .andReturn().jsonPath();
        List<Usuario> usuarios = path.getList("list", Usuario.class);

        assertEquals(mauricio, usuarios.get(0));
        assertEquals(guilherme, usuarios.get(1));

    }

    @Test
    public void deveRetornarUsuarioPorIdJson() {
        JsonPath path = given()
                .header("Accept", "application/json")
                .param("usuario.id", 1)
                .get("/usuarios/show")
                .andReturn().jsonPath();

        Usuario usuario = path.getObject("usuario", Usuario.class);
        assertEquals(mauricio, usuario);

    }

    @Test
    public void deveAdicionarUmUsuario() {
        XmlPath xpath = 
            given()
                .header("Accept", "application/xml")
                .contentType("application/xml")
                .body(joao)
            .expect()
                .statusCode(200)
            .when()
                .post("/usuarios")
            .andReturn()
                .xmlPath();

        Usuario resposta = xpath.getObject("usuario", Usuario.class);
        assertEquals(joao.getNome(), resposta.getNome());
        assertEquals(joao.getEmail(), resposta.getEmail());

        given()
        .contentType("application/xml")
        .body(resposta)
    .expect()
        .statusCode(200)
    .when()
        .delete("/usuarios/deleta")
    .andReturn()
        .asString();
    }
}

A aplicação que provê os serviços tem algum bug?

Sim, foi detectado um bug nos métodos "delete" e "find" dos serviços de Leilões e de Usuários. No caso de leilões, o problema só irá se manifestar após a criação do leilão de id 128; já para os usuários, o bug só não se manifesta com os dois primeiros (id 1 e 2); nos demais, por serem criados com IDs maiores que 127, o erro se manifesta.

O bug está relacionado com a forma de se comparar dois valores Long, que não deveria usar o operador ==.

Esse problema foi reportado recentemente à Caelum.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software