Testing non-activity classes in Android

旧时模样 提交于 2020-01-22 17:45:26

问题


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:

  1. create a test project
  2. create a test case
  3. 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.



来源:https://stackoverflow.com/questions/5830825/testing-non-activity-classes-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!