在当前框架中,我们有一个扩展ActivityInstrumentationTestCase2的基类。 Android开发人员。通常,当我们编写测试用例类时,我们会继承该基类(我们称其为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上得到一个空指针。

最佳答案

您可以传入整个测试类并为其建立一个构造函数。

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();
}

07-24 09:25