2011-10-09 27 views
5

我有一個Jersey資源,我想用JUnit測試。資源使用吉斯提供商注入某些領域:單元測試Jersey資源與Guice注入字段

@Path("/example/") 
class ExampleResource { 
    @Inject 
    Provider<ExampleActionHandler> getMyExampleActionHandlerProvider; 

    @GET 
    @Produces(MediaType.APPLICATION_JSON) 
    public List<ExamplePojo> getExampleList() { 
     ExampleActionHandler handler = getMyExampleActionHandlerProvider.get(); 
     handler.doSomething(); 
    ... 

使用一個真正的服務器來服務API時,這所有的工作很漂亮,但是測試它是有問題的。

我的測試類現在看起來是這樣的:

public class ApiTest extends JerseyTest { 

    public ApiTest() throws Exception { 
    super(); 
    ApplicationDescriptor appDescriptor = new ApplicationDescriptor(); 
    appDescriptor.setContextPath("/api"); 
    appDescriptor.setRootResourcePackageName("com.my.package.name"); 
    super.setupTestEnvironment(appDescriptor); 
    } 

    @Test 
    public void testHelloWorld() throws Exception { 
    String responseMsg = webResource.path("example/").get(String.class); 
    Assert.assertEquals("{}", responseMsg); 
    } 
} 

顯然,吉斯沒有得到機會來初始化ExampleResource所以字段的handler.doSomething()調用不會導致空指針異常。

有沒有辦法告訴Jersey使用Guice實例化ExampleResource類,以便提供程序工作?

+1

我知道這是一個有點晚,但關閉的機會,你看到的仍然是這個,那你最終會做什麼? – talon8

+0

@minichate你有這個工作嗎? –

回答

0

一種方法是將測試分解爲幾個步驟。您需要創建您正在配置該服務的進樣器並測試該進樣器(請參閱Testing Guice Servlet bindingsTesting Guice can init servlets)。使用這些測試你確保你有正確的綁定。 一旦你的噴油器,從它那裏得到的ApplicationDescriptor對象與

ExampleResource exampleResource = injector.getInstance(ExampleResource.class); 
Assert.assertEquals(myList, getExampleList()); 
+0

這種方法的問題是澤西沒有什麼魔術可用 - 比如@DefaultValue()註釋字段。我實際上已經按照我想要的方式獲得了這種工作方式,只是試圖將其包裝到SO上的後期能力中。 – minichate

+0

你是如何得到這個工作的? – bobK

相關問題