How to Unit Test in Android Development

In JavaEE, there is a Junit test package

In the development of Android, we have to use some classes developed by Google

code show as below:

Here's a calculator class to test:

package org.dreamtech.helloworld;

public  class Calc {
     // Calculator class

    public int add(int x, int y) {
        return x + y;
    }
}

 

Add this line under the configuration file:

 <application
        android:allowBackup="true"
        android:enabled="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

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

        <activity
            android:name="org.dreamtech.helloworld.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

Add these lines outside:

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="org.dreamtech.helloworld" />

 

Write a test class:

package org.dreamtech.helloworld;

import android.test.AndroidTestCase;

public class Test extends AndroidTestCase {
    public void testAdd() {
        Calc calc = new Calc();
         int result = calc.add(3, 5 );
         // Assert: the first parameter is the expected value 
        assertEquals(8 , result);
    }
}

 

test was successful!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325686858&siteId=291194637