从另一个类运行runTestOnUiThread

时间:2014-08-12 00:54:17

标签: android android-instrumentation

在我们当前的框架中,我们有一个扩展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上得到一个空指针。

1 个答案:

答案 0 :(得分: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();
}