【问题标题】:How to add multi-parameterized unit tests in the same test class如何在同一个测试类中添加多参数化单元测试
【发布时间】:2017-04-06 08:38:27
【问题描述】:

我的 android 应用程序中有一个 java 类,其中包含两个或多个接受不同参数集合的方法。如何编写包含多参数化单元测试的测试类?

提示:问题是当我编写带有注解@RunWith(Parameterized.class) 的测试类时,它只接受一个参数化单元测试。

【问题讨论】:

    标签: android junit


    【解决方案1】:

    有几个选项可以使用不同的参数集运行测试。

    JUnit 参数化

    您可以使用 Enclosed runner 在另一个类中使用不同的测试类。

    @RunWith(Enclosed.class)
    public class TestClass {
    
        @RunWith(Parameterized.class)
        public static class FirstParameterizedTest {
    
            @Parameters
            public static Object[][] data() {
                ...
            }
    
            @Test
            public void someTest() {
                ...
            }
        }
    
        public static class SecondParameterizedTest {
    
            @Parameters
            public static Object[][] data() {
                ...
            }
    
            @Test
            public void anotherTest() {
                ...
            }
        }
    }
    

    JUnitParams

    JUnitParams 有很多方法可以指定参数。见https://github.com/Pragmatists/JUnitParams/blob/master/src/test/java/junitparams/usage/SamplesOfUsageTest.java

    这是一个简单的例子。

    @RunWith(JUnitParamsRunner.class)
    public class TestClass {
    
        @Test
        @Parameters({"AAA,1", "BBB,2"})
        public void paramsInAnnotation(String p1, Integer p2) {
            ...
        }
    }
    

    爆发

    Burst 使用枚举来指定测试参数。不同的测试方法可以使用不同的枚举。

    @RunWith(BurstJUnit4.class)
    public class TestClass {
        enum FirstSetOfParameters {
            A(1,2),
            B(2,3)
    
            final int x1, x2;
    
            FirstSetOfParameters( int x1, int x2) {
                this.x1=x1;
                this.x2=x2;
            }
        }
    
        @Test
        public void firstTest( FirstSetOfParameters parameters) {
            ...
        }
    
        enum SecondSetOfParameters {
            A(1),
            B(2)
    
            final int x1;
    
            SecondSetOfParameters(int x1) {
                this.x1=x1;
            }
        }
    
        @Test
        public void secondTest(SecondSetOfParameters parameters) {
            ...
        }
    }
    

    其他库

    还有一些库。你可以看看Zohhak和junit-dataprovider。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多