2013-04-06 3 views
0

Я хотел бы высмеять ответ клиента RESTEasy в моих тестах JUnit с телом ответа из содержимого в предопределенных xml-файлах. Рассмотрим следующие Person обслуживания клиента API и Person лица:Как высмеять ответ службы REST на стороне клиента?

package my.company.com; 

import java.net.URI; 

import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlRootElement; 

import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.Credentials; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.CookieStore; 
import org.apache.http.client.protocol.ClientContext; 
import org.apache.http.impl.client.BasicCookieStore; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.protocol.BasicHttpContext; 
import org.apache.http.protocol.HttpContext; 
import org.jboss.resteasy.client.ClientRequest; 
import org.jboss.resteasy.client.ClientResponse; 
import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor; 

public class PersonServiceClient { 
    private final DefaultHttpClient httpClient; 

public PersonServiceClient(String username, String password) { 
    Credentials credentials = new UsernamePasswordCredentials(username, password); 
    httpClient = new DefaultHttpClient(); 
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); 
} 

public Person[] getPersons() throws Exception 
{ 
    URI url = new URI("http://www.mycompany.com/persons/"); 
    Person[] persons = getByRest(url, Person[].class); 
    return persons; 
} 

private <T> T getByRest(URI url, Class<T> returnType) throws Exception { 
    ClientRequest client = createClientRequest(url.toString()); 
    ClientResponse<T> response = client.get(returnType); 
    return response.getEntity(); 
} 

private ClientRequest createClientRequest(String url) { 
    // Storing cookie to avoid creating new client for every call 
    CookieStore cookieStore = new BasicCookieStore(); 
    HttpContext httpContext = new BasicHttpContext(); 
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 
    ApacheHttpClient4Executor clientExecutor = new ApacheHttpClient4Executor(httpClient, httpContext); 

    ClientRequest clientRequest = new ClientRequest(url, clientExecutor); 
    return clientRequest; 
} 

@XmlRootElement(name = "resource") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Person { 
    private String type; 
    private String name; 
    private String addres; 
    private String phone; 

    public String getType() { 
     return type; 
    } 

    public void setType(String type) { 
     this.type= type; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getAddres() { 
     return addres; 
    } 

    public void setAddres(String addres) { 
     this.addres = addres; 
    } 

    public String getPhone() { 
     return phone; 
    } 

    public void setPhone(String phone) { 
     this.phone = phone; 
    } 

    public Person() { 
    } 
} 
} 

и содержание ответа-test1.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<collection> 
    <resource> 
     <type>Peson</type> 
     <name>Christopher Monroe</name> 
     <addres>Wall Street 2</addres> 
     <phone>12345678</<phone> 
    </resource> 
    <resource> 
     <type>Person</type> 
     <name>John Dee</name> 
     <addres>Down town 2</addres> 
     <phone>2997562123</phone> 
    </resource> 
</collection> 

Как я могу издеваться тело ответа в тесте JUnit ниже с содержанием от ответа -test.xml файл выше?

@Test 
public void testGetPersons() throws Exception{ 
    PersonServiceClient client = new PersonServiceClient("joe", "doe"); 
    Person[] persons = client.getPersons(); 
} 

Я пытался следовать примеру в этом посте Is there a client-side mock framework for RESTEasy?, но он не показывает точно, как выбрать тело ответа.

+0

ли Вы, доработан любое решение еще Ismar? –

ответ

0

Рассмотрите возможность использования фабрики для создания ClientRequest, затем издевайтесь над фабрикой, чтобы вернуть макет ClientRequest.

1

Вместо насмешливый клиента Resteasy, я предложил бы насмехаясь сервер, используя WireMock (отказ от ответственности - я написал): http://wiremock.org/

Это настраивается с помощью беглого Java API внутри JUnit и подбегает встроенный веб сервер, который обслуживает отпечатанные ответы и позволяет вам проверять запросы, отправленные из вашего приложения.

Я написал об основаниях для не издевается HTTP клиентов в немного более подробно здесь: Introducing WireMock

Смежные вопросы