【问题标题】:Randomise the order of instrumentation tests随机化仪器测试的顺序
【发布时间】:2013-11-28 18:01:45
【问题描述】:

我想知道是否可以随机化运行仪器测试的顺序,即那些扩展 ActivityInstrumentationTestCase2。我尝试关注this blog post,但我不知道如何告诉测试框架我希望使用我的测试运行器。

问题是我不能使用 @RunWith 注释,因为这些是(据我了解)JUnit3 测试,而不是 JUnit4。

这很可能毫无意义,因为它们不需要随机化,但以这种方式证明测试的独立性会很好。

理想情况下,我希望首先使用命令行和 gradle 包装器运行它。

然后,如果可能的话,最好让它通过 Android Studio 工作。

[编辑]

当您执行“编辑配置...”时,我可以看到在 AS 中,可以通过“特定仪表运行器(可选)”框在那里指定您自己的运行器。不幸的是,如果我这样做,我会收到以下错误:

Test running startedTest running failed: Unable to find instrumentation info for: ComponentInfo{<path_to_class_here>.RandomizingTestRunner}
Empty test suite.

我不知道为什么。

【问题讨论】:

    标签: android unit-testing junit4 junit3


    【解决方案1】:

    您可以使用以下随机运行器:

    package com.example.test.runners;
    
    import android.test.InstrumentationTestRunner;
    import android.test.suitebuilder.TestSuiteBuilder;
    import junit.framework.Test;
    import junit.framework.TestSuite;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    public class RandomizedInstrumentationTestRunner extends InstrumentationTestRunner {
    
     @Override
     public TestSuite getTestSuite() {
        return buildTestSuite();
     }
    
     private TestSuite buildTestSuite() {
        TestSuiteBuilder builder = new TestSuiteBuilder(getClass().getName(), getTargetContext().getClassLoader());
        builder.includePackages("");
    
        List<Test> tests = new ArrayList<Test>();
        addTestsFromSuite(builder.build(), tests);
        Collections.shuffle(tests);
    
        TestSuite randomizedSuite = new TestSuite();
        for (Test one : tests) {
            randomizedSuite.addTest(one);
        }
    
        return randomizedSuite;
     }
    
    
     private void addTestsFromSuite(TestSuite suite, List<Test> out) {
        List<Test> tests = Collections.list(suite.tests());
        for (Test one : tests) {
            if (one instanceof TestSuite) {
                     addTestsFromSuite((TestSuite) one, out);
                 }
                 else{
                     out.add(one);
                 }
            }
      }
    }
    

    别忘了在你的 build.gradle 文件中设置跑步者:

    android {
    
       defaultConfig {
           testInstrumentationRunner "com.example.test.runners.RandomizedInstrumentationTestRunner"
           minSdkVersion 8
       }
    
       ....
    }
    

    最后运行以下两次,验证随机执行顺序:

    ./gradlew connectedCheck --info
    

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多