AndroidTestCase 為一 Android 平臺(tái)下通用的測(cè)試類,它支持所有 JUnit 的 Assert 方法和標(biāo)準(zhǔn)的 setUp 和 tearDown 方法。如果你的測(cè)試需要訪問(wèn)應(yīng)用的資源或者測(cè)試方法依賴於 Context,可以使用 AndroidTestCase 作為基類。
它的類繼承關(guān)係如下圖所示:
http://wiki.jikexueyuan.com/project/android-test-course/images/15.1.jpg" alt="picture15.1" />
Focus2AndroidTest 測(cè)試也是 Android ApiDemos 示例解析(116):Views->Focus->2. Horizontal
但測(cè)試的側(cè)重點(diǎn)不一樣,F(xiàn)ocus2AndroidTest 測(cè)試的內(nèi)容無(wú)需啟動(dòng) Activity,而是測(cè)試 R.layout.focus_2 的布局(資源)中 Focus 的順序是否符合預(yù)先設(shè)計(jì)(可以看作是 Activity 的一些靜態(tài)性能),可以通過(guò) FocusFinder 的方法來(lái)測(cè)試 Focus 的一些靜態(tài)屬性,它的代碼如下:
public class Focus2AndroidTest
extends AndroidTestCase {
private FocusFinder mFocusFinder;
private ViewGroup mRoot;
private Button mLeftButton;
private Button mCenterButton;
private Button mRightButton;
@Override
protected void setUp() throws Exception {
super.setUp();
mFocusFinder = FocusFinder.getInstance();
// inflate the layout
final Context context = getContext();
final LayoutInflater inflater = LayoutInflater.from(context);
mRoot = (ViewGroup) inflater.inflate(R.layout.focus_2, null);
// manually measure it, and lay it out
mRoot.measure(500, 500);
mRoot.layout(0, 0, 500, 500);
mLeftButton = (Button) mRoot.findViewById(R.id.leftButton);
mCenterButton = (Button) mRoot.findViewById(R.id.centerButton);
mRightButton = (Button) mRoot.findViewById(R.id.rightButton);
}
@SmallTest
public void testPreconditions() {
assertNotNull(mLeftButton);
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());
}
@SmallTest
public void testGoingRightFromLeftButtonJumpsOverCenterToRight() {
assertEquals("right should be next focus from left",
mRightButton,
mFocusFinder.findNextFocus(mRoot, mLeftButton,
View.FOCUS_RIGHT));
}
@SmallTest
public void testGoingLeftFromRightButtonGoesToCenter() {
assertEquals("center should be next focus from right",
mCenterButton,
mFocusFinder.findNextFocus(mRoot, mRightButton,
View.FOCUS_LEFT));
}
}
testGoingRightFromLeftButtonJumpsOverCenterToRight 和 testGoingLeftFromRightButtonGoesToCenter
通過(guò) mFocusFinder 的 findNextFocus 來(lái)測(cè)試 mLeftButton,mRightButton 的下個(gè)可以獲取焦點(diǎn)的控制項(xiàng)是否符合事先的設(shè)計(jì)。