通过AndroidTestCase来进行android 单元测试

来源:互联网 发布:最强围棋软件 编辑:程序博客网 时间:2024/05/17 06:03

介绍过了如何用intrumentation进行android单元测试,其实还有一种方法同样可以,那就是利用AndroidTestCase来做单元测试,intrumentationTestCaseAndroidTestCase都是Junit.framwork.TestCase的子类,二者代表不用的方向。

 

如果想通过AndroidTestCase,大致可以通过以下几个步骤实现:

1.       添加自己的test case code, 让他们继承自AndroidTestCase。

2.       定义自己的testSuite类,用来管理test cases.

3.       定义自己的testRunner,用来执行测试

下面首先来看一下这种方法所涉及到的android的类以及接口。

AndroidTestCase

Android test cases classes需要从这个类派生出来,而不再是从junit.framework.TestCase. 二者之间的最主要区别就是Android test cases提供了一个方法getContext()来获取当前的上下文变量,这在android测试中很重要的,因为很多的android api都需要context。

AndroidTestCase主要成员:

setUp() //Sets up the fixture, for example, open a network connection.

tearDown() //Tears down the fixture, for example, close a network connection.

testAndroidTestCaseSetupProperly()

TestSuite (in package junit.package)

一个TestSuite就是一系列test case的集合。通过testsuite可以更好的来管理test case

 

TestSuite主要成员:

 Void addTest (Test test) //Adds a test to the suite.

void addTestSuite(Class testClass) //Adds the tests from the given class to the suite

下面是一小段往test suite中添加test case的示例:

 TestSuite suite= new TestSuite();
 suite.addTest(new MathTest("testAdd")); //Adds a test to the suite.
 suite.addTest(new MathTest("testDivideByZero"));
或者可以通过addTestSuite()来添加:
suite.addTestSuite(MathTest.class); 
 

TestListener (in package junit.framework)

 

这是一个 interface ,用来监听测试进程

有以下4个Public Methods :

abstract void addError(Test test,Throwable t)

An error occurred.

abstract void addFailure(Test test,AssertionFailedError t)

A failure occurred.

abstract void endTest(Test test)

A test ended.

abstract void startTest(Test test)

A test started.

AndroidTestRunner

继承自class junit.runner.BaseTestRunner,但是它没有提供ui, 甚至来一个基于console的UI都没有,所以,如果想要很好的查看测试结果的话,你需要自己来处理来自于test runner的callback 函数。一会可以通过例子演示一下

AndroidTestRunner主要方法:

SetTest();

runTest()

addTestListener()

setContext()

如果要使用AndroidTestRunner,需要permission in manifest.xml中添加权限:

<uses-library android:name="android.test.runner" />

最后,通过一个实例来演示一下:

1.       写一个test case:

MathTest.java


package com.ut.prac;
  
import android.test.AndroidTestCase;
import android.util.Log; 

public class MathTest extends AndroidTestCase {
    protected int i1;
    protected int i2;
    static final String LOG_TAG = "MathTest";

    public void setUp() {
        i1 = 2;
        i2 = 3;
    } 
    public void testAdd() {
        Log.d( LOG_TAG, "testAdd" );
        assertTrue( LOG_TAG+"1", ( ( i1 + i2 ) == 5 ) );
    }

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


2.  定义一个test suite类。

ExampleSuite.java




package com.ut.prac;

import junit.framework.TestSuite;

public class ExampleSuite extends TestSuite {
    public ExampleSuite() {
        addTestSuite( MathTest.class );
    }
}


原创粉丝点击