Java generics: how to port / extend the test version of Android Activity?

I am trying to extend ActivityInstrumentationTestCase2 as follows:

public abstract class FooActivityTestCase<T extends Activity> extends ActivityInstrumentationTestCase2<Activity> { public FooActivityTestCase(String pckg, Class<Activity> activityClass) { super(pckg, activityClass); } public void foo(){ ... } } 

I am trying to extend FooActivityTestCase as follows:

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

Eclipse gives me the following error in the constructor:

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

I am sure the problem is with how I use generics. When SpecificFooTestCase extends ActivityInstrumentationTestCase2 , I get no errors. Can someone point out what I'm doing wrong?


Offers Kublai Khan and Michael Myers work together. After I changed FooActivityTestCase to extend ActivityInstrumentationTestCase2<T> and Class<Activity> to Class<T> in the constructor, the classes compile without errors. This is the resulting class (SpecificFooTestCase has not changed):

 public abstract class FooActivityTestCase<T extends Activity> extends ActivityInstrumentationTestCase2<T> { public FooActivityTestCase(String pckg, Class<T> activityClass) { super(pckg, activityClass); } public void foo(){ ... } } 
+4
source share
2 answers

You need to define a super constructor as follows:

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

The thing is, for generics arguments, the generic type must always be the exact same generic type , if you want to be able to pass something in the inheritance tree, do you need to use a wildcard ? and extends ? and extends , so you can pass it some kind of generic type that extends this class.

+3
source

Here's how I do Android device testing:

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

And define your test classes as such:

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

All Articles