2016-03-20 66 views
0

我是JerseyTest的新手。我已經爲我的控制器創建了幾個單元測試,通過了解主題上的許多帖子以及本網站上的各種問題。我正在使用InMemoryTestContainerFactory,因爲我的測試非常簡單。但是,在設置期間似乎沒有設置baseUri的方法。我的目標是什麼?我的測試類繼承以下的類:使用InMemoryTestContainerFactory時爲JerseyTest設置baseUrl

public abstract class ApiTest extends JerseyTest { 

    @Override 
    protected TestContainerFactory getTestContainerFactory() { 
     return new InMemoryTestContainerFactory(); 
    } 

    @Override 
    protected ResourceConfig configure() { 
     ResourceConfig rc = new ResourceConfig() 
       .register(SpringLifecycleListener.class) 
       .register(RequestContextFilter.class) 
       .register(this) 
       .property("contextConfig", new AnnotationConfigApplicationContext(ApplicationConfiguration.class)); 

     enable(TestProperties.LOG_TRAFFIC); 
     enable(TestProperties.DUMP_ENTITY); 
     forceSet(TestProperties.CONTAINER_PORT, "0"); 

     return configure(rc); 
    } 

    protected abstract ResourceConfig configure(ResourceConfig rc); 
} 

樣品測試類:

public class ResourceTest extends ApiTest { 

    private final Client webClient = ClientBuilder.newClient(); 

    @Rule 
    public ExpectedException thrown = ExpectedException.none(); 

    @Mock 
    private ResourceService service; 

    @Before 
    public void setUp() throws Exception { 
     initMocks(this); 
    } 

    @Override 
    protected ResourceConfig configure(ResourceConfig rc) { 
     rc.register(Resource.class); 
     return rc; 
    } 

    @Test 
    public void testGetResource() { 

     Response response = webClient 
       .target("http://localhost:8080") 
       .path("/resource") 
       .queryParam("id", "some_id_json") 
       .request(MediaType.APPLICATION_JSON_TYPE) 
       .get(); 

     assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST)); 
     assertThat(response.readEntity(Errors.class).getMessages().get(0), isA(String.class)); 
    } 
} 

本網站提供的示例代碼似乎都不被配置baseUri(見this爲例)。然而,如果我將它設置爲任意值http://localhost:xxx,我會拒絕連接(顯然?)。如果我將它設置爲僅路徑,我會收到錯誤base URL is not absolute

回答

1

您可以覆蓋JerseyTest中的URI getBaseUri()。默認是localhost:9998

但是你並不需要使用它。 JerseyTest已經有ClientWebTarget(從getBaseUri建成)爲您設置。您只需致電target即可獲得,例如

Response response = target().request().get(); 
// or 
Response response = target("path").request().get(); 
+0

第一個給我一個'NullPointerException'。第二個抱怨URL不是絕對的。我可以看到基本URI設置爲「http:// localhost:0」。我猜測問題是設置容器。 – 341008

+0

我一直在尋找一個小時來找到這個問題的答案; 9998端口的祕密已經隱藏起來了,並且似乎從JerseyTest官方文檔頁面中缺少。 localhost:9998是問題的答案,應該被接受。 – tekHedd

0

發現問題。我沒有調用super.setUp()覆蓋了setUp(),結果沒有調用TestContainer.start()

相關問題