Android 从其他类运行runTestOnUiThread
在我们当前的框架中,我们有一个扩展ActivityInstrumentationTestCase2 | Android开发者的基类。通常,当我们编写测试用例类时,我们会继承这个基类(我们称之为FooBase)并编写我们的方法。正如您所想象的,这变得越来越大,我想对它进行重构,以便对于我们正在测试的功能的每个区域,它都在自己的类中,以便我们可以重用它。希望我的vague类足够准确,目标只是能够将方法拆分为不同的类,并从我的测试用例中调用它们Android 从其他类运行runTestOnUiThread,android,android-instrumentation,Android,Android Instrumentation,在我们当前的框架中,我们有一个扩展ActivityInstrumentationTestCase2 | Android开发者的基类。通常,当我们编写测试用例类时,我们会继承这个基类(我们称之为FooBase)并编写我们的方法。正如您所想象的,这变得越来越大,我想对它进行重构,以便对于我们正在测试的功能的每个区域,它都在自己的类中,以便我们可以重用它。希望我的vague类足够准确,目标只是能够将方法拆分为不同的类,并从我的测试用例中调用它们 public class FooBase extend
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());
}
}
public void testRun(){
baseTestCase.getCurrentActivity();
}