java - 如何使用 Junit 创建可共享的测试包?
问题描述
假设我在 中创建了一个模块化项目maven
,其中api
定义了接口,在和中定义myproject-api
了该接口的两个实现。myproject-impl
myproject-impl2
myproject-api
myproject-impl
myproject-impl2
我想创建一个测试套件,我可以针对这两种实现运行。当然,将来我可以添加另一个实现,并且我还想使用这些常见测试对其进行测试。
用junit实现这种共享测试的最佳实践是什么?
接口示例(中myproject-api
):
public interface SmallLettersSource {
String read();
}
实现:
- 在模块中
myproject-impl
:
class ASource implements SmallLettersSource {
@Override
public String read() {
return "a";
}
}
- 在模块中
myproject-impl2
:
class BSource implements SmallLettersSource {
@Override
public String read() {
return "b";
}
}
并测试(我也想将它添加到myproject-api
):
@Test
void test() {
assert(source.read().equals(source.read().toLowerCase()));
}
解决方案
我想出了以下解决方案:
在
myproject-api
我创建了类CommonTestSuite
,它返回DynamicTest
对象列表:public class CommonTestSuite { private final Source source; public CommonTestSuite(Source source) { this.source = source; } public Collection<DynamicTest> tests() { return Arrays.asList( dynamicTest("Should return only lowercase.", this::testLowercase), dynamicTest("Should return only one letter.", this::testLength) ); } void testLowercase() { assert(source.read().equals(source.read().toLowerCase())); } void testLength() { assert(source.read().size() == 1); } }
- 然后在我的实现模块的测试中,我只需要做:
class MyProjectImplTest { @TestFactory Collection<DynamicTest> test() { return new CommonTestSuite(new ASource()).tests(); } }
对于其他模块,我需要进行类似的设置。这样我就可以在各个模块之间共享通用测试。
推荐阅读
- vuejs3 - Vue 3 为 svgPanZoom 加载脚本,但未定义函数
- python - 在 Python 中按顺序导入和插入单词
- html - 多选项表单不显示
- java - vaadin(14.4.4)应用程序:无法确定开发模式的项目目录...在部署之前生成“flow-build-info.json”
- android - 如何开始为图像捕获创建自定义相机意图?
- javascript - 如何在python eel中的多个javascript文件之间进行通信
- python - 选择列表的索引被给定值整除时出错
- python - 使用openCV从图像中去除直线噪声
- reactjs - 获取请求未更新状态
- webgl - 使用 WebGL2 渲染到带有 alpha 混合的帧缓冲区时的伪影