2012-12-24 204 views
4

我正在编写一个使用Jersey下的引擎向Java RESTful API(第三方)发送HTTP请求的Java类。如何模拟Jersey REST客户端抛出HTTP 500响应?

我还想编写一个JUnit测试来模拟发送HTTP 500响应的API。作为新泽西州的新手,我很难看到我必须做些什么来模拟这些HTTP 500响应。

到目前为止,这是我最好的尝试:

// The main class-under-test 
public class MyJerseyAdaptor { 
    public void send() { 
     ClientConfig config = new DefaultClientConfig(); 
     Client client = Client.create(config); 
     String uri = UriBuilder.fromUri("http://example.com/whatever").build(); 
     WebResource service = client.resource(uri); 

     // I *believe* this is where Jersey actually makes the API call... 
     service.path("rest").path("somePath") 
       .accept(MediaType.TEXT_HTML).get(String.class); 
    } 
} 

@Test 
public void sendThrowsOnHttp500() { 
    // GIVEN 
    MyJerseyAdaptor adaptor = new MyJerseyAdaptor(); 

    // WHEN 
    try { 
     adaptor.send(); 

     // THEN - we should never get here since we have mocked the server to 
     // return an HTTP 500 
     org.junit.Assert.fail(); 
    } 
    catch(RuntimeException rte) { 
     ; 
    } 
} 

我熟悉不过的Mockito在嘲讽库中没有偏好。基本上,如果有人可以告诉我需要嘲笑哪些类/方法来抛出HTTP 500响应,我可以弄清楚如何实际执行这些模拟。

回答

4

试试这个:

WebResource service = client.resource(uri); 

WebResource serviceSpy = Mockito.spy(service); 

Mockito.doThrow(new RuntimeException("500!")).when(serviceSpy).get(Mockito.any(String.class)); 

serviceSpy.path("rest").path("somePath") 
      .accept(MediaType.TEXT_HTML).get(String.class); 

我不知道的球衣,但是从我的理解,我想调用get()方法时,实际调用完成。 因此,您只需使用真实的WebResource对象并替换get(String)方法的行为来抛出异常,而不是实际执行http调用。

1

我正在编写一个Jersey web应用程序......并且我们为HTTP错误响应抛出了WebApplicationException。您可以简单地将响应代码作为构造函数参数传递。例如,

throw new WebApplicationException(500); 

当服务器端引发此异常时,它在我的浏览器中显示为500 HTTP响应。

不知道这是你想要的...但我认为输入可能有帮助!祝你好运。

+0

谢谢@ ktm5124(+1) - 但我需要从*客户端*嘲笑这一点。这是我打的第三方API,所以我不能在服务器代码中嘲笑任何东西。再次感谢! – IAmYourFaja

+0

ClientHandlerException是您需要的类吗?我没有和泽西客户合作过,所以我可能会在这里黑暗中。顺便说一句,谢谢你把我放在魔鬼的标记之上! – ktm5124

相关问题