Java泛型:如何包装/扩展Android Activity测试用例?

时间:2011-08-10 19:36:06

标签: java android generics

我正在尝试按如下方式扩展ActivityInstrumentationTestCase2:

public abstract class FooActivityTestCase<T extends Activity>
  extends ActivityInstrumentationTestCase2<Activity> {

  public FooActivityTestCase(String pckg, Class<Activity> activityClass)
  {
    super(pckg, activityClass);
  }

  public void foo(){ ... }
}

我尝试像这样扩展FooActivityTestCase

public class SpecificFooTestCase
  extends FooActivityTestCase<MyActivity> {
  public SpecificFooTestCase() {
    super("foo.bar", MyActivity.class);  // error on this line
  }
}

Eclipse在构造函数中给出了以下错误:

The constructor FooActivityTestCase<MyActivity>(String, Class<MyActivity>) is undefined

我很确定问题在于我如何使用泛型。当SpecificFooTestCase延长ActivityInstrumentationTestCase2时,我不会收到任何错误。谁能指出我做错了什么?


忽必烈汗和迈克尔迈尔斯的建议一起工作。在构造函数中更改FooActivityTestCase以将ActivityInstrumentationTestCase2<T>Class<Activity>扩展为Class<T>之后,这些类将无错误地编译。这是结果类(SpecificFooTestCase没有改变):

public abstract class FooActivityTestCase<T extends Activity>
  extends ActivityInstrumentationTestCase2<T> {

  public FooActivityTestCase(String pckg, Class<T> activityClass)
  {
    super(pckg, activityClass);
  }

  public void foo(){ ... }
}

2 个答案:

答案 0 :(得分:3)

你需要像这样定义超级构造函数:

//Only accepts classes that are Activity or extend Activity
 public FooActivityTestCase(String pckg, Class<? extends Activity> activityClass)
      {
        super(pckg, activityClass);
      }

问题是,对于泛型参数,泛型类型 必须始终完全相同的泛型类型 ,如果您希望能够在继承树中传递某些内容你需要使用通配符? and extends,这样你就可以传递任何扩展该类的泛型类型。

答案 1 :(得分:-2)

这是我进行Android单元测试的方式:

public class MyInstrumentationTestRunner extends InstrumentationTestRunner 
{
    @Override
    public TestSuite getAllTests() 
    {
        InstrumentationTestSuite suite = new InstrumentationTestSuite(this);
        suite.addTestSuite(MyTestClass.class);
        return suite;
    }

    @Override
    public ClassLoader getLoader() 
    {
        return MyInstrumentationTestRunner.class.getClassLoader();
    }
}

并定义您的测试类:

public class myTestClass extends
    ActivityInstrumentationTestCase2<Home> 
{
    Context _context;

    public MyTestClass() 
    {
        super("com.MyClassToTest", Home.class);
    }

    public void testfunction() 
    {
        myFunction(_context);
    }

    @Override
    protected void setUp() throws Exception 
    {
        super.setUp();
        setActivityInitialTouchMode(false);
        Activity activity = getActivity();
        _context = activity.getApplicationContext();
    }
}