Android测试教程(15):AndroidTestCase示例

AndroidTestCase 为一Android平台下通用的测试类,它支持所有JUnit的Assert方法和标准的setUp 和tearDown 方法。如果你的测试需要访问应用的资源或者测试方法依赖于Context,可以使用AndroidTestCase 作为基类。

它的类继承关系如下图所示:

Focus2AndroidTest 测试也是Android  ApiDemos示例解析(116):Views->Focus->2. Horizontal

但测试的侧重点不一样,Focus2AndroidTest 测试的内容无需启动Activity,而是测试R.layout.focus_2 的布局(资源)中Focus 的顺序是否符合预先设计(可以看作是Activity的一些静态性能),可以通过FocusFinder的方法来测试Focus的一些静态属性,它的代码如下:

 

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

通过mFocusFinder 的 findNextFocus 来测试 mLeftButton,mRightButton 的下个可以获取焦点的控件是否符合事先的设计。

你可能感兴趣的:(android,exception,测试,JUnit,layout,button)