2017-02-15 80 views
6

我有一個觸發並執行偵聽應用就緒事件來調用外部服務獲取一些數據,然後使用一個類彈簧啓動應用程序該數據將一些規則推送到類路徑以供執行。對於本地測試,我們有嘲笑我們的應用程序內的外部服務,它在應用程序啓動過程中工作正常。解析端口已在使用的春天開機測試定義的端口

問題,同時通過與春天開機測試註釋和嵌入式碼頭集裝箱無論是在運行它測試應用:

  • 隨機端口
  • 定義的端口

在case RANDOM PORT,在應用程序啓動時,它從模擬服務的URL中獲取屬性文件在一個已定義的端口,並且不知道嵌入容器在哪裏運行,因爲它是隨機選取的,因此無法給出響應。

如果是DEFINED PORT,對於第一個測試用例文件它運行成功,但下一個文件被拾取的時候,它會失敗,說明該端口已被使用。

這些測試用例在多個文件邏輯分區,需要 外部服務容器啓動時加載 規則之前調用。

如何在使用定義的端口的情況下在測試文件之間共享嵌入式容器或重構我的應用程序代碼,而不是在測試用例執行期間啓動時獲取隨機端口。

任何幫助,將不勝感激。

應用程序啓動代碼:

@Component 
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent> { 

@Autowired 
private SomeService someService; 

@Override 
public void onApplicationEvent(ApplicationReadyEvent arg0) { 

    try { 
     someService.callExternalServiceAndLoadData(); 
    } 
    catch (Execption e) {} 
    } 
} 

測試代碼註釋:Test1的

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) 
@TestPropertySource("classpath:test-application.properties") 
public class Test1 { 

    @Autowired 
    private TestRestTemplate restTemplate; 

    @Test 
    public void tc1() throws IOException {.....} 

測試代碼註釋:Test2的

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) 
@TestPropertySource("classpath:test-application.properties") 
public class Test2 { 

    @Autowired 
    private TestRestTemplate restTemplate; 

    @Test 
    public void tc1() throws IOException {.....} 
+1

我有一個類似的問題。你有沒有找到解決方案? – unwichtich

回答

0

我跑過同一個問題。我知道這個問題有點老,但這可能是有幫助的:

使用@SpringBootTest(webEnvironment = WebEnvironment。RANDOM_PORT)也可以注入的實際端口到字段通過使用@LocalServerPort註釋,如圖以下示例:

來源:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-user-a-random-unassigned-http-port

給出的代碼的例子是:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) 
public class MyWebIntegrationTests { 

    @Autowired 
    ServletWebServerApplicationContext server; 

    @LocalServerPort 
    int port; 

    // ... 

} 
相關問題