android.test.ActivityInstrumentationTestCase2
一、在Manifest.xml加入
<uses-library android:name="android.test.runner" /><uses-permission android:name="android.permission.RUN_INSTRUMENTATION" /><instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.travelsky.android.test"android:label="Test for my app"/>
二、編寫單元測試代碼:必須繼承自AndroidTestCase類
package com.travelsky.android.test; import android.test.AndroidTestCase;import junit.framework.Assert; public class MyTest extends AndroidTestCase {private static final String Tag="MyTest"; public void testSave() throws Throwable{int i=4+8;Assert.assertEquals(5,i);} public void testSomethingElse() throws Throwable {Assert.assertTrue(1 + 1 == 12);} }
run--> Android JUnit Test
運行後會,會出現如下警告:
Warning: No instrumentation runner found for the launch, using
android.test.InstrumentationTestRunner.
模擬器不能記住Androidmanifest的配置,在運行時需要重新設定回合組態,如下:
1.在工程名字上點擊右鍵,選擇properties
2.在Run/Debug setting中選擇要啟動並執行工程名字,點擊右邊的Edit,會進入下面的介面,
在 instrumentation runner後面的下拉式清單中選擇:android.test.InstrumentationTestRunner
3.重新運行該測試單元,則就不會出現上面的警告了。
還可以繼承android.test.ActivityInstrumentationTestCase2<T>
添加建構函式
添加setUp()方法,這個方法在所有的測試之前進行變數和測試環境的初始化。
@Override protected void setUp() throws Exception { super.setUp(); mActivity = this.getActivity(); mView = (TextView) mActivity.findViewById(com.example.helloandroid.R.id.textview); resourceString = mActivity.getString(com.example.helloandroid.R.string.hello); }添加testPreconditions()方法,檢查初始化環境,只執行一次public void testPreconditions() { assertNotNull(mView); }添加單元測試public void testText() { assertEquals(resourceString,(String)mView.getText()); }
這時候會遇到這樣一個問題, 啟動並執行時候提示Test run failed: Test run incomplete. Expected 1 tests, received 0。
後來找到是建構函式的事,於是把泛型去掉, 然後用不帶參數的建構函式,在建構函式裡調用super(“com.travelsky.test”, ActivityName.class); 就Ok了。
REFERENCES:http://www.189works.com/article-19108-1.html
http://www.cnblogs.com/GnagWang/archive/2011/07/08/2101066.html
http://www.cnblogs.com/feisky/archive/2012/03/09/1783826.html