Android JUnit深入浅出(五)——AndroidTest例子分析

来源:互联网 发布:北京鑫宇昊辰网络 编辑:程序博客网 时间:2024/05/19 13:10

前面我们学习了android.test包中的大部分类,是该通过学习具体的例子将前面的知识融会贯通,让我们的理解更加深刻,例子程序代码在本文末有下载,下载后添加Eclipes的工程中,边看这篇文章边阅读例子程序的代码。


首先分析整个工程的结构图,如下:

Android JUnit深入浅出(五)——AndroidTest例子分析_27909

AndroidTestCase,Testsuite在前面的篇幅中已经学习过了,ContestTest、MathTest、SomeTest、ExampleSuite在前面的例子中已经为大家介绍了,这里我们主要说明整个程序是如何运行的?

核心类代码简要列举,如下:
  1. public class JUnit extends Activity {
  2. static final String LOG_TAG = “junit”;
  3. Thread testRunnerThread = null;
  4. /** Called when the activity is first created. */
  5. @Override
  6. public void onCreate(Bundle savedInstanceState)
  7. {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.main);
  10. Button launcherButton = (Button)findViewById( R.id.launch_button );
  11. launcherButton.setOnClickListener( new View.OnClickListener() {
  12. public void onClick( View view ) {startTest();}
  13. } );
  14. }
  15. private synchronized void startTest()
  16. {
  17. if( ( testRunnerThread != null ) &&!testRunnerThread.isAlive() )
  18. testRunnerThread = null;
  19. if( testRunnerThread == null )
  20. {
  21. testRunnerThread = new Thread( new TestRunner( this ) );
  22. testRunnerThread.start();
  23. }
  24. else
  25. {
  26. Toast.makeText(this, “Test is still running”, Toast.LENGTH_SHORT).show();
  27. }

  28. class TestRunner implements Runnable,TestListener
  29. {
  30. static final String LOG_TAG = “TestRunner”;
  31. int testCounter;
  32. int errorCounter;
  33. int failureCounter;
  34. ……;
  35. Activity parentActivity;

  36. public TestRunner( Activity parentActivity )
  37. {this.parentActivity = parentActivity;}

  38. public void run()
  39. {
  40. testCounter = 0;
  41. errorCounter = 0;
  42. failureCounter = 0;
  43. ………….;

  44. Log.d( LOG_TAG, “Test started” );
  45. /*整个代码的核心*/
  46. AndroidTestRunner testRunner = new AndroidTestRunner();
  47. testRunner.setTest( new ExampleSuite() );
  48. testRunner.addTestListener( this );
  49. testRunner.setContext( parentActivity );
  50. testRunner.runTest();
  51. Log.d( LOG_TAG, “Test ended” );
  52. }

  53. // TestListener
  54. public void addError(Test test, Throwable t)
  55. {
  56. Log.d( LOG_TAG, “addError: “+test.getClass().getName() );
  57. Log.d( LOG_TAG, t.getMessage(), t );
  58. ++errorCounter;
  59. …….;
  60. }

  61. public void addFailure(Test test, AssertionFailedError t)
  62. {
  63. Log.d( LOG_TAG, “addFailure: “+test.getClass().getName() );
  64. Log.d( LOG_TAG, t.getMessage(), t );
  65. ++failureCounter;
  66. …….;
  67. }

  68. public void endTest(Test test)
  69. {
  70. Log.d( LOG_TAG, “endTest: “+test.getClass().getName() );
  71. …..;
  72. }

  73. public void startTest(Test test)
  74. {
  75. Log.d( LOG_TAG, “startTest: “+test.getClass().getName() );
  76. ++testCounter;
  77. …….;
  78. }

  79. }
复制代码
通过将源工程中的代码简单整理后,就可以看到TestRunner这个工作者线程(window中的术语,没有界面的线程)的作用,这让我们对TestListener有了更加深入的了解。