1

在我们当前的框架中,我们有一个扩展 ActivityInstrumentationTestCase2 | 的基类。安卓开发者。通常,当我们编写测试用例类时,我们会继承这个基类(我们称之为 FooBase)并编写我们的方法。正如您可以想象的那样,它变得非常大,我想重构它,以便对于我们正在测试的功能的每个区域,它都在它自己的类中,以便我们可以重用它。希望我的模糊类足够准确目标只是能够将方法分成不同的类并从我的测试用例中调用它们

 public class FooBase extends ActivityInstrumentionTestCase2 {
    @Override
 public void runTestOnUiThread(Runnable runnable) {
    try {
        super.runTestOnUiThread(runnable);
    } catch (InterruptedException e) {
        throw RuntimeInterruptedException.rethrow(e);
    } catch (RuntimeException e) {
        throw e;
    } catch (Error e) {
        throw e;
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
 }
 } 

我们的测试将是例如

public class TestFooBase extends FooBase{
      public void testfeature(){
               //execute a method that uses super.runTestOnUiThread()
      }

 }

我如何尝试重构它

 public class FooHelper extends FooBase{
     public FooHelper(Activity activity){
         setActivity(activity)
     }
     public void sameMethod(){
         //moved the method in FooBase to this class that uses the runTestOnUiThread
     }

}

我的新测试用例看起来像这样

public class TestFooBase extends FooBase{
      FooHelper fooHelper;
      public void setup(){
              fooHelper = new FooHelper(getActivity);
      }
      public void testfeature(){
               //execute a method that uses super.runTestOnUiThread()
               fooHelper.callthemethod()
      }

 }

当我执行这个时,我在 super.runTestOnUIThread 上得到一个空指针。

4

1 回答 1

1

您可以传入整个测试类并为其设置构造函数。

public class BaseTestCase {
    private Instrumentation instrumentation;
    private InstrumentationTestCase instrumentationTestCase;

    public BaseTestCase(InstrumentationTestCase testClass, Instrumentation instrumentation){
        this.instrumentationTestCase = testClass;
        this.instrumentation = instrumentation;
}

    public Activity getCurrentActivity() {
        try {
            instrumentationTestCase.runTestOnUiThread(new Runnable() {
                @Override
                public void run() {
                   //Code
                }
            });
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return activity;

}

要使用,您要在 setUp 方法上实例化 BaseTestCase 类

public class ActivityTest extends ActivityInstrumentationTestCase2<TestActivity.class>{
    private BaseTestCase baseTestCase;
    @Override
    public void setUp() throws Exception { 
        super.setUp();
        getActivity();
        baseTestCase = new BaseTestCase(this, getInstrumentation());
    }
}

并访问 BaseTestCase 中的公共方法

public void testRun(){
    baseTestCase.getCurrentActivity();
}
于 2014-08-27T01:03:06.127 回答