Android单元测试2-工具

来源:互联网 发布:电脑锣编程群 编辑:程序博客网 时间:2024/06/11 04:06

Android测试官方指导文档主要在两个地方:

http://developer.android.com/

1 . Tools-->Workflow--->Testing

2. Training-->Best Practices For Testing


主要说明了以下几个类:

1. TestCase

    JUnit的测试类


2.AndroidTestCase

   类似TestCase, 提供了一个获取Android Context的方法。


3. ActivityUnitTestCase

  独立测试Activity, 控制其生命周期等


4. ActivityInstrumentationTestCase2

  Activity的功能测试, 可以发送按键事件, 可以联合测试多个Activity


5. ServiceTestCase

  测试Service

6. ProviderTestCase2 

  测试 Content providers


###########  分割线 ##############

TestCase的用法:

public class CalculateTest extends TestCase {protected void setUp() throws Exception {super.setUp();}public void testAdd() {Calculate cal = new Calculate();int ret = cal.add(10, 20);System.out.println("ret = "+ret);assertEquals(30, ret);}protected void tearDown() throws Exception {super.tearDown();}}


AndroidTeseCase的用法:

public class CalculateAndroidTest extends AndroidTestCase {private View mainView;private TextView text;@Overrideprotected void setUp() throws Exception {// TODO Auto-generated method stubsuper.setUp();final Context context = getContext();        final LayoutInflater inflater = LayoutInflater.from(context);        mainView = (ViewGroup) inflater.inflate(R.layout.activity_main, null);                text = (TextView) mainView.findViewById(R.id.test_text);        }@Overrideprotected void tearDown() throws Exception {// TODO Auto-generated method stubsuper.tearDown();}public void testSetTextView() {assertNotNull(text);text.setText("aaa");}@Overridepublic void testAndroidTestCaseSetupProperly() {// TODO Auto-generated method stubsuper.testAndroidTestCaseSetupProperly();}}


ActivityUnitTestCase的用法:

public class CalculateAndroidUnitTest extends ActivityUnitTestCase<MainActivity> {private Intent mStartIntent;public CalculateAndroidUnitTest() {super(MainActivity.class);}@Overrideprotected void setUp() throws Exception {// TODO Auto-generated method stubsuper.setUp();System.out.println("setUp ------");mStartIntent = new Intent(Intent.ACTION_MAIN);}@MediumTest    public void testPreconditions() {System.out.println("testPreconditions ------");        startActivity(mStartIntent, null, null);                assertNotNull(getActivity());    }@Overrideprotected void tearDown() throws Exception {// TODO Auto-generated method stubsuper.tearDown();System.out.println("tearDown ------");}@MediumTestpublic void testLifeCycleCreate() {MainActivity activity = startActivity(mStartIntent, null, null);                // At this point, onCreate() has been called, but nothing else        // Complete the startup of the activity        getInstrumentation().callActivityOnStart(activity);                getInstrumentation().callActivityOnResume(activity);                // At this point you could test for various configuration aspects, or you could         // use a Mock Context to confirm that your activity has made certain calls to the system        // and set itself up properly.                getInstrumentation().callActivityOnPause(activity);                // At this point you could confirm that the activity has paused properly, as if it is        // no longer the topmost activity on screen.                getInstrumentation().callActivityOnStop(activity);}}


ActivityInstrumentationTestCase2的用法:

public class Focus2ActivityTest extends ActivityInstrumentationTestCase2<Focus2> {    private Button mLeftButton;    private Button mCenterButton;    private Button mRightButton;    /**     * Creates an {@link ActivityInstrumentationTestCase2} that tests the {@link Focus2} activity.     */    public Focus2ActivityTest() {        super(Focus2.class);    }    @Override    protected void setUp() throws Exception {        super.setUp();        final Focus2 a = getActivity();        // ensure a valid handle to the activity has been returned        assertNotNull(a);        mLeftButton = (Button) a.findViewById(R.id.leftButton);        mCenterButton = (Button) a.findViewById(R.id.centerButton);        mRightButton = (Button) a.findViewById(R.id.rightButton);    }    /**     * The name 'test preconditions' is a convention to signal that if this     * test doesn't pass, the test case was not set up properly and it might     * explain any and all failures in other tests.  This is not guaranteed     * to run before other tests, as junit uses reflection to find the tests.     */    @MediumTest    public void testPreconditions() {        assertTrue("center button should be right of left button",                mLeftButton.getRight() < mCenterButton.getLeft());        assertTrue("right button should be right of center button",                mCenterButton.getRight() < mRightButton.getLeft());        assertTrue("left button should be focused", mLeftButton.isFocused());    }    @MediumTest    public void testGoingRightFromLeftButtonJumpsOverCenterToRight() {        sendKeys(KeyEvent.KEYCODE_DPAD_RIGHT);        assertTrue("right button should be focused", mRightButton.isFocused());    }    @MediumTest    public void testGoingLeftFromRightButtonGoesToCenter()  {        // Give right button focus by having it request focus.  We post it        // to the UI thread because we are not running on the same thread, and        // any direct api calls that change state must be made from the UI thread.        // This is in contrast to instrumentation calls that send events that are        // processed through the framework and eventually find their way to        // affecting the ui thread.        getActivity().runOnUiThread(new Runnable() {            public void run() {                mRightButton.requestFocus();            }        });        // wait for the request to go through        getInstrumentation().waitForIdleSync();        assertTrue(mRightButton.isFocused());        sendKeys(KeyEvent.KEYCODE_DPAD_LEFT);        assertTrue("center button should be focused", mCenterButton.isFocused());    }}




0 0
原创粉丝点击