Created
July 27, 2013 15:29
-
-
Save mneedham/6095162 to your computer and use it in GitHub Desktop.
Playing around with a simple stub of a jersey client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import com.sun.jersey.api.client.Client; | |
| import com.sun.jersey.api.client.ClientHandlerException; | |
| import com.sun.jersey.api.client.ClientRequest; | |
| import com.sun.jersey.api.client.ClientResponse; | |
| import org.junit.Test; | |
| import static org.junit.Assert.assertEquals; | |
| public class RandomTest { | |
| @Test | |
| public void jerseyFailingExample() { | |
| Client client = client().requestFor("http://www.google.com").returns(500).create(); | |
| String result = new Foo(client).doSomething(); | |
| assertEquals("fail", result); | |
| } | |
| @Test | |
| public void jerseyWinningExample() { | |
| Client client = client().requestFor("http://www.google.com").returns(200).create(); | |
| String result = new Foo(client).doSomething(); | |
| assertEquals("win", result); | |
| } | |
| private ClientBuilder client() { | |
| return new ClientBuilder(); | |
| } | |
| class ClientBuilder { | |
| private String uri; | |
| private int statusCode; | |
| public ClientBuilder requestFor(String uri) { | |
| this.uri = uri; | |
| return this; | |
| } | |
| public ClientBuilder returns(int statusCode) { | |
| this.statusCode = statusCode; | |
| return this; | |
| } | |
| public Client create() { | |
| return new Client() { | |
| public ClientResponse handle(ClientRequest request) throws ClientHandlerException { | |
| if(request.getURI().toString().equals(uri)) { | |
| return new ClientResponse(statusCode, null, null, null); | |
| } | |
| throw new RuntimeException("No stub provided for " + request.getMethod() + " " + request.getURI()); | |
| } | |
| }; | |
| } | |
| } | |
| class Foo { | |
| private Client httpClient; | |
| public Foo(Client httpClient) { | |
| this.httpClient = httpClient; | |
| } | |
| public String doSomething() { | |
| ClientResponse response = httpClient.resource("http://www.google.com").get(ClientResponse.class); | |
| if(response.getStatus() >= 100 && response.getStatus() < 400) { | |
| return "win"; | |
| } else { | |
| return "fail"; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment