并編寫如下代碼:
package com.mamlambo.article.simplecalc.test;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;
import android.widget.Button;
import com.mamlambo.article.simplecalc.MainActivity;
import com.mamlambo.article.simplecalc.R;
public class LayoutTests extends ActivityInstrumentationTestCase2 {
private Button addValues;
private Button multiplyValues;
private View mainLayout;
public LayoutTests() {
super("com.mamlambo.article.simplecalc", MainActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
MainActivity mainActivity = getActivity();
addValues = (Button) mainActivity.findViewById(R.id.addValues);
multiplyValues = (Button) mainActivity
.findViewById(R.id.multiplyValues);
mainLayout = (View) mainActivity.findViewById(R.id.mainLayout);
}
}
這里,分別獲得了加法按鈕和乘法按鈕的實例。接下來,增加一個testAddButtonOnScreen
的方法,以測試按鈕的位置是否正確。在這個方法中,首先你要決定屏幕的大小。有很多方
法去檢測屏幕的大小,比如用getWidth()和getHeight()方法,當然在考慮尺寸時,還必須考
慮象標題欄,狀態欄等所占用的位置大小。下面是其代碼:
public void testAddButtonOnScreen() {
int fullWidth = mainLayout.getWidth();
int fullHeight = mainLayout.getHeight();
int[] mainLayoutLocation = new int[2];
mainLayout.getLocationOnScreen(mainLayoutLocation);
int[] viewLocation = new int[2];
addValues.getLocationOnScreen(viewLocation);
Rect outRect = new Rect();
addValues.getDrawingRect(outRect);
assertTrue("Add button off the right of the screen", fullWidth
+ mainLayoutLocation[0] > outRect.width() + viewLocation[0]);
assertTrue("Add button off the bottom of the screen", fullHeight
+ mainLayoutLocation[1] > outRect.height() + viewLocation[1]);
}
在各類尺寸的模擬器上運行,可以得到如下結果所示的測試結果:
480x800, portrait 模式 (通過)
800x480, landscape mode (失敗)
320x480, portrait mode (失敗)
480x320, landscape (失敗)
480x854, portrait mode (通過)
854x480, landscape mode (失敗)?
大家可以思考下為什么有的測試用例成功有的失敗。
總結
本文講解了如何使用junit配合Android的應用進行單元測試及詳細步驟,以及如何在
Junit測試Android時的小技巧?梢钥吹,在設計完應用后應該編寫單元測試用例,測試用
例越多和越詳細,則對程序的正確性提高越有好處。
文章來源于領測軟件測試網 http://www.k11sc111.com/