您的位置:知识库 » 软件测试

在Android上实现Junit单元测试的四部曲

来源: JavaEye  发布时间: 2010-10-17 22:44  阅读: 2237 次  推荐: 0   原文链接   [收藏]  
摘要:本文讲述在Android上实现Junit单元测试,利用JUnit等单元测试框架进行单元测试对于Java程序员并不陌生,利用这些非常有效的工具,使得代码的质量得到有效的监控和维护。

  我们曾经和大家探讨过全面剖析Java ME单元测试理念,其实在Android上实现JUnit单元测试也不是很困难,主要是在配置文件和测试环境上将花费很长时间,下面从四步简单讲一下在Android上实现Junit单元测试。

  第一步:新建一个TestCase,记得要继承androidTestCase,才能有getContext()来获取当前的上下文变量,这在Android测试中很重要的,因为很多的Android api都需要context。

  Java代码

public class TestMath extends AndroidTestCase {

private int i1;
private int i2;
static final String LOG_TAG = "MathTest";

@Override
protected void setUp() throws Exception {
i1
= 2;
i2
= 3;
}

public void testAdd() {
assertTrue(
"testAdd failed", ((i1 + i2) == 5));
}

public void testDec() {
assertTrue(
"testDec failed", ((i2 - i1) == 1));
}

@Override
protected void tearDown() throws Exception {
super.tearDown();
}

@Override
public void testAndroidTestCaseSetupProperly() {
super.testAndroidTestCaseSetupProperly();
//Log.d( LOG_TAG, "testAndroidTestCaseSetupProperly" ;
}

}

  第二步:新建一个TestSuit,这个就继承Junit的TestSuite就可以了,注意这里是用的addTestSuite方法,一开始使用addTest方法就是不能成功。

  Java代码

public class ExampleSuite extends TestSuite {

public ExampleSuite() {
addTestSuite(TestMath.
class);
}

}

  第三步:新建一个Activity,用来启动单元测试,并显示测试结果。系统的AndroidTestRunner竟然什么连个UI界面也没有实现,这里只是最简单的实现了一个

  Java代码

代码
1. public class TestActivity extends Activity {
2.
3. private TextView resultView;
4.
5. private TextView barView;
6.
7. private TextView messageView;
8.
9. private Thread testRunnerThread;
10.
11. private static final int SHOW_RESULT = 0;
12.
13. private static final int ERROR_FIND = 1;
14.
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.main);
19. resultView = (TextView)findViewById(R.id.ResultView);
20. barView = (TextView)findViewById(R.id.BarView);
21. messageView = (TextView)findViewById(R.id.MessageView);
22. Button lunch = (Button)findViewById(R.id.LunchButton);
23. lunch.setOnClickListener(new View.OnClickListener() {
24. @Override
25. public void onClick(View v) {
26. startTest();
27. }
28. });
29. }
30.
31. private void showMessage(String message) {
32. hander.sendMessage(hander.obtainMessage(ERROR_FIND, message));
33. }
34.
35. private void showResult(String text) {
36. hander.sendMessage(hander.obtainMessage(SHOW_RESULT, text));
37. }
38.
39. private synchronized void startTest() {
40. if (testRunnerThread != null
41. && testRunnerThread.isAlive()) {
42. testRunnerThread = null;
43. }
44. if (testRunnerThread == null) {
45. testRunnerThread = new Thread(new TestRunner(this));
46. testRunnerThread.start();
47. } else {
48. Toast.makeText(this,
49. "Test is still running",
50. Toast.LENGTH_SHORT).show();
51. }
52. }
53.
54. public Handler hander = new Handler() {
55. public void handleMessage(Message msg) {
56. switch (msg.what) {
57. case SHOW_RESULT:
58. resultView.setText(msg.obj.toString());
59. break;
60. case ERROR_FIND:
61. messageView.append(msg.obj.toString());
62. barView.setBackgroundColor(Color.RED);
63. break;
64. default:
65. break;
66. }
67. }
68. };
69.
70. class TestRunner implements Runnable, TestListener {
71.
72. private Activity parentActivity;
73.
74. private int testCount;
75.
76. private int errorCount;
77.
78. private int failureCount;
79.
80. public TestRunner(Activity parentActivity) {
81. this.parentActivity = parentActivity;
82. }
83.
84. @Override
85. public void run() {
86. testCount = 0;
87. errorCount = 0;
88. failureCount = 0;
89.
90. ExampleSuite suite = new ExampleSuite();
91. AndroidTestRunner testRunner = new AndroidTestRunner();
92. testRunner.setTest(suite);
93. testRunner.addTestListener(this);
94. testRunner.setContext(parentActivity);
95. testRunner.runTest();
96. }
97.
98. @Override
99. public void addError(Test test, Throwable t) {
100. errorCount++;
101. showMessage(t.getMessage() + "\n");
102. }
103.
104. @Override
105. public void addFailure(Test test, AssertionFailedError t) {
106. failureCount++;
107. showMessage(t.getMessage() + "\n");
108. }
109.
110. @Override
111. public void endTest(Test test) {
112. showResult(getResult());
113. }
114.
115. @Override
116. public void startTest(Test test) {
117. testCount++;
118. }
119.
120. private String getResult() {
121. int successCount = testCount - failureCount - errorCount;
122. return "Test:" + testCount + " Success:" + successCount + " Failed:" + failureCount + " Error:" + errorCount;
123. }
124.
125. }
126.
127. }

  第四步:修改AndroidManifest.xml,加入,不然会提示找不到AndroidTestRunner,这里需要注意是这句话是放在applications下面的,我一开始也不知道,放错了地方,浪费了不少时间

  Xml代码

xml version="1.0" encoding="utf-8"?>
<manifest xmlns:Android="http://schemas.Android.com/apk/res/Android"
package
="com.test.sample"
Android:versionCode
="1"
Android:versionName
="1.0">
<application Android:icon="@drawable/icon"
       Android:label
="@string/app_name" Android:debuggable="true">
<activity Android:name=".TestActivity"
Android:label
="@string/app_name">
<intent-filter>
<action Android:name="Android.intent.action.MAIN" />
<category Android:name="Android.intent.category.LAUNCHER" />
intent-filter>
activity>
<uses-library Android:name="Android.test.runner" />
application>
<uses-sdk Android:minSdkVersion="4" />
manifest>

0
0

软件测试热门文章

    软件测试最新文章

      最新新闻

        热门新闻