我的代码库很古老,并被锁在JUnit4中。我希望将测试容器与在自动化测试中包含坞容器的项目集成在一起。
我的开发框(我控制的)运行坞,然而,我的CI系统(我不控制)不运行。
如果我可以使用JUnit5,我只需添加@Testcontainers(disabledWithoutDocker = true)注释,基于端口的测试将在我的开发框上愉快地运行,同时在CI机器上被禁用。
什么是JUnit4等同于@Testcontainers(disabledWithoutDocker = true)?
发布于 2020-06-24 06:43:45
我不确定JUnit 4的测试容器中是否有现成的特性,您可以用一些自定义代码来反映JUnit 5的特性。
首先,需要一种有条件地执行测试的方法。已经有一个可用的good answer。基本上,您可以使用JUnit 4假设来实现这一点:
@Before
public void beforeMethod() {
org.junit.Assume.assumeTrue(someCondition());
// rest of setup.
}所有与码头相关的测试都需要这个。
接下来,someCondition()应该评估Docker是否可用。当前的测试容器(1.14.3)版本为@Testcontainers(disabledWithoutDocker = true)使用了以下代码部分
private ConditionEvaluationResult evaluate(Testcontainers testcontainers) {
if (testcontainers.disabledWithoutDocker()) {
if (isDockerAvailable()) {
return ConditionEvaluationResult.enabled("Docker is available");
}
return ConditionEvaluationResult.disabled("disabledWithoutDocker is true and Docker is not available");
}
return ConditionEvaluationResult.enabled("disabledWithoutDocker is false");
}
boolean isDockerAvailable() {
try {
DockerClientFactory.instance().client();
return true;
} catch (Throwable ex) {
return false;
}
}因此,您可以将isDockerAvailable()提取到例如也包含@Before的抽象类中,并自己处理:
public abstract class DockerizedTest {
@Before
public void shouldRunTest() {
org.junit.Assume.assumeTrue(isDockerAvailable());
}
boolean isDockerAvailable() {
try {
DockerClientFactory.instance().client();
return true;
} catch (Throwable ex) {
return false;
}
}
}现在,所有与Docker相关的测试都可以扩展DockerizedTest。当假设值为false时,测试将被忽略。
如果@Before太晚了,您可以对@BeforeClass使用相同的方法。
https://stackoverflow.com/questions/62546724
复制相似问题