首页 > 解决方案 > 如何使用 Junit 创建可共享的测试包?

问题描述

假设我在 中创建了一个模块化项目maven,其中api定义了接口,在和中定义myproject-api了该接口的两个实现。myproject-implmyproject-impl2

myproject-api
myproject-impl
myproject-impl2

我想创建一个测试套件,我可以针对这两种实现运行。当然,将来我可以添加另一个实现,并且我还想使用这些常见测试对其进行测试。

用junit实现这种共享测试的最佳实践是什么?

接口示例(中myproject-api):

public interface SmallLettersSource {
   String read();
}

实现:

class ASource implements SmallLettersSource {

    @Override
    public String read() {
        return "a";
    }
}
class BSource implements SmallLettersSource {

    @Override
    public String read() {
        return "b";
    }
}

并测试(我也想将它添加到myproject-api):

@Test
void test() {
    assert(source.read().equals(source.read().toLowerCase()));
}

标签: javamavenjunit

解决方案


我想出了以下解决方案:

  1. 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);
        }
    }
    
    
    1. 然后在我的实现模块的测试中,我只需要做:
    class MyProjectImplTest {
    
        @TestFactory
        Collection<DynamicTest> test() {
           return new CommonTestSuite(new ASource()).tests();
        }
    }
    

    对于其他模块,我需要进行类似的设置。这样我就可以在各个模块之间共享通用测试。


推荐阅读