2017-02-15 38 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; 

    // ... 

} 
相关问题