Preloader image

Este é um exemplo básico sobre como configurar e utilizar o Cliente Rest do MicroProfile no TomEE.

mvn clean test

Requisitos e configuração

Para usar o MicroProfile Rest Client, são necessárias 3 alterações no seu projeto:

  1. Adicione a seguinte dependência ao pom.xml:

     <dependency>
         <groupId>org.eclipse.microprofile.rest.client</groupId>
         <artifactId>microprofile-rest-client-api</artifactId>
         <version>${version.microprofile.rest-client}</version>
         <scope>provided</scope>
     </dependency>
  2. Forneça o arquivo de configuração: microprofile-config.properties

     org.superbiz.rest.BookResourceClient/mp-rest/url=http://localhost:4444
  3. Forneça uma interface que você possa criar a partir do recurso JAX-RS que deseja consumir: BookResourceClient.java

     package org.superbiz.rest;
    
     import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
     import jakarta.enterprise.context.Dependent;
     import jakarta.ws.rs.*;
     import jakarta.ws.rs.core.MediaType;
     import java.util.List;
    
     @Dependent
     @RegisterRestClient
     @Path("/test/api/library")
     @Produces(MediaType.APPLICATION_JSON)
     @Consumes(MediaType.APPLICATION_JSON)
     public interface BookResourceClient {
    
         @GET
         String status();
    
         @POST
         @Path("/books")
         void addBook(Book newBook);
    
         @DELETE
         @Path("/books/{id}")
         void deleteBook(@PathParam("id") int id);
    
         @PUT
         @Path("/books")
         void updateBook(Book updatedBook);
    
         @GET
         @Path("/books/{id}")
         Book getBook(@PathParam("id") int id);
    
         @GET
         @Path("/books")
         List<Book> getListOfBooks();
    
     }

Usando o Client Rest do MicroProfile no TomEE

A classe BookResourceTest.java mostra como é fácil usar a abordagem de segurança de tipo fornecida pelo MicroProfile Client Rest para consumir um recurso JAX-RS existente.

package org.superbiz.rest;

import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

import jakarta.inject.Inject;

import static org.junit.Assert.assertTrue;

@RunWith(Arquillian.class)
public class BookResourceTest {

    @Deployment()
    public static WebArchive createDeployment() {
        final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "test.war")
                .addClass(BookResource.class)
                .addClass(Book.class)
                .addClass(BookBean.class)
                .addClass(BookResourceClient.class)
                .addClass(ApplicationConfig.class)
                .addAsWebInfResource(new StringAsset("<beans/>"), "beans.xml")
                .addAsResource("META-INF/microprofile-config.properties");
        return webArchive;
    }


    @Inject
    @RestClient
    private BookResourceClient bookResourceClient;

    @Test()
    public void testServerStatus(){
        bookResourceClient.addBook(new Book(1,"TomEE Book"));
    }

    @Test
    public void testBookResource(){
        bookResourceClient.addBook(new Book(1, "TomEE and MicroProfile Adventures"));
        bookResourceClient.addBook(new Book(2, "Top 10 Tomee Configuraiton Tips"));


        assertTrue(bookResourceClient.getListOfBooks().size() == 2);
        assertTrue(bookResourceClient.getBook(1).getName().equalsIgnoreCase("TomEE and MicroProfile Adventures"));

        bookResourceClient.deleteBook(1);
        assertTrue(bookResourceClient.getListOfBooks().size() == 1);
        assertTrue(bookResourceClient.getBook(2).getName().equalsIgnoreCase("Top 10 Tomee Configuraiton Tips"));

        bookResourceClient.updateBook(new Book(2, "Top 3 Tomee Configuraiton Tips"));
        assertTrue(bookResourceClient.getListOfBooks().size() == 1);
        assertTrue(bookResourceClient.getBook(2).getName().equalsIgnoreCase("Top 3 Tomee Configuraiton Tips"));
    }

}

Sobre a arquitetura de teste

Os casos de teste para este projeto são criados usando o Arquillian e o TomEE Remote. A configuração do Arquillian pode ser encontrada em src/test/resources/arquillian.xml.