ahj*_*ish 9 java integration-testing spring-boot spring-boot-test
我有一个Spring启动应用程序,它启动并执行一个类,它监听Application Ready事件以调用外部服务来获取一些数据,然后使用该数据将一些规则推送到类路径以便执行.对于本地测试,我们在应用程序启动期间模拟了应用程序中的外部服务.
该问题是在测试与运行它的应用程序春天开机测试注释和嵌入式码头集装箱无论是在:
在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) {}
}
}
Run Code Online (Sandbox Code Playgroud)
测试代码注释: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 {.....}
Run Code Online (Sandbox Code Playgroud)
测试代码注释: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 {.....}
Run Code Online (Sandbox Code Playgroud)
小智 19
如果您坚持在多个测试中使用相同的端口,您可以通过使用以下内容注释您的测试类来防止 spring 缓存上下文以进行进一步的测试:@DirtiesContext
在你的情况下:
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@TestPropertySource("classpath:test-application.properties")
Run Code Online (Sandbox Code Playgroud)
这是安迪·威尔金森 (Andy Wilkinson) 对本次讨论的回答的引述
这是按设计工作的。默认情况下,Spring Framework 的测试框架会缓存上下文以供多个测试类可能重用。您有两个具有不同配置的测试(由于@TestPropertySource),因此它们将使用不同的应用程序上下文。第一个测试的上下文将被缓存并在第二个测试运行时保持打开状态。两个测试都配置为对 Tomcat 的连接器使用相同的端口。结果,当运行第二个测试时,由于端口与第一个测试中的连接器发生冲突,上下文无法启动。您有几个选择:
- 使用 RANDOM_PORT
- 从 Test2 中删除 @TestPropertySource 以便上下文具有相同的配置,并且第一个测试中的上下文可以重用于第二个测试。
- 使用 @DirtiesContext 以便不缓存上下文
我遇到了同样的问题。我知道这个问题有点老了,但这可能有帮助:
使用@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;
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9315 次 |
| 最近记录: |