技术开发 频道

使用Junit对Android应用进行单元测试

  步骤15 Android中对屏幕显示的单元测试

  在Android 的单元测试中,还可以针对界面的显示位置等进行单元测试。比如我们在Eclipse时开发采用的界面模拟器是在800*480的模式下的,但如果在其他尺寸规格的移动设备上是否能正常运行呢?这就需要对界面设置部分进行单元测试了。

  我们另外创建一个单元测试用例,用前文所讲的方法新建立一个名为LayoutTests的单元测试用例,如下图:

十五、Android中对屏幕显示的测试

  并编写如下代码:

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时的小技巧。可以看到,在设计完应用后应该编写单元测试用例,测试用

  例越多和越详细,则对程序的正确性提高越有好处。

0