I know how to test Activity classes with JUnit 4 in Android but I am unable to understand how to test non-activity classes (which don't extends Activity, ListActivity, or some other Activity class, but uses some Android APIs). Please help me in this regard.
问题:
回答1:
To test non activity classes:
- create a test project
- create a test case
run as Android JUnit Test
public class MyClassTests extends TestCase { /** * @param name */ public myClassTests(String name) { super(name); } /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } /** * Test something */ public final void testSomething() { fail("Not implemented yet"); } }
回答2:
The Android SDK includes JUnit. In fact, the Android test classes such as AndroidTestCase and InstrumentationTestCase inherit from junit.framework.TestCase. This means that you can use a standard JUnit test case to test a non-Activity class and include it in Android Projects.
For example, you can create an Android Project with a simple class to test:
public class MyClass {
public static int getOne() {
return 1;
}
}
and an Android Test Project with a standard JUnit test to test this class:
public class TestMyClass extends TestCase {
public void testMyClass() {
assertEquals(1, MyClass.getOne());
}
}
and run this on an Android device or on the Android emulator.
More information after seeing clarification of question in the comments:
AndroidTestCase or other Android test classes can be used to test non-Activity classes which need access to the rest of the Android framework (with a dummy activity provided in the setUp() if necessary). These give you access to a Context if you need to, for example, bind to a service.