AndroidでJunitユニットテストを実現


もともとandroidでユニットテストを実現するのは、簡単なことだと思っていたが、結局、ファイルの構成やテスト環境に多くの時間を費やし、想像以上に複雑だったが、あまり深いものはなく、簡単に話した.
ステップ1:新しいTestCaseを作成し、Android TestCaseを継承してこそ、getContext()を使用して現在のコンテキスト変数を取得することができます.これはandroidテストで重要です.多くのandroid apiにはcontextが必要です.
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メソッドを使用すると成功しません.
public class ExampleSuite extends TestSuite {
	
	public ExampleSuite() {
		addTestSuite(TestMath.class);
	}

}

ステップ3:ユニットテストを開始し、テスト結果を表示するActivityを新規作成します.システムのAndroid TestRunnerはUIインタフェースも何も実現していない.ここでは最も簡単な実現にすぎない.
public class TestActivity extends Activity {
	
	private TextView resultView;
	
	private TextView barView;
	
	private TextView messageView;
	
	private Thread testRunnerThread;
	
	private static final int SHOW_RESULT = 0;
	
	private static final int ERROR_FIND = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		resultView = (TextView)findViewById(R.id.ResultView);
		barView = (TextView)findViewById(R.id.BarView);
		messageView = (TextView)findViewById(R.id.MessageView);
		Button lunch = (Button)findViewById(R.id.LunchButton);
		lunch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startTest();
			}
		});
	}
	
	private void showMessage(String message) {
		hander.sendMessage(hander.obtainMessage(ERROR_FIND, message));
	}
	
	private void showResult(String text) {
		hander.sendMessage(hander.obtainMessage(SHOW_RESULT, text));
	}
	
	private synchronized void startTest() {
		if (testRunnerThread != null
				&& testRunnerThread.isAlive()) {
			testRunnerThread = null;
		}
		if (testRunnerThread == null) {
			testRunnerThread = new Thread(new TestRunner(this));
			testRunnerThread.start();
		} else {
			Toast.makeText(this, 
					"Test is still running", 
					Toast.LENGTH_SHORT).show();
		}
	}
	
	public Handler hander = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case SHOW_RESULT:
					resultView.setText(msg.obj.toString());
					break;
				case ERROR_FIND:
					messageView.append(msg.obj.toString());
					barView.setBackgroundColor(Color.RED);
					break;
				default:
					break;
			}
		}
	};
	
	class TestRunner implements Runnable, TestListener {
	
		private Activity parentActivity;
		
		private int testCount;
		
		private int errorCount;
		
		private int failureCount;
		
		public TestRunner(Activity parentActivity) {
			this.parentActivity = parentActivity;
		}

		@Override
		public void run() {
			testCount = 0;
			errorCount = 0;
			failureCount = 0;
			
			ExampleSuite suite = new ExampleSuite();
			AndroidTestRunner testRunner = new AndroidTestRunner();
			testRunner.setTest(suite);
			testRunner.addTestListener(this);
			testRunner.setContext(parentActivity);
			testRunner.runTest();
		}

		@Override
		public void addError(Test test, Throwable t) {
			errorCount++;
			showMessage(t.getMessage() + "
"); } @Override public void addFailure(Test test, AssertionFailedError t) { failureCount++; showMessage(t.getMessage() + "
"); } @Override public void endTest(Test test) { showResult(getResult()); } @Override public void startTest(Test test) { testCount++; } private String getResult() { int successCount = testCount - failureCount - errorCount; return "Test:" + testCount + " Success:" + successCount + " Failed:" + failureCount + " Error:" + errorCount; } } }

ステップ4:AndroidManifestを修正します.xml,,さもないとAndroidTestRunnerが見つからないことをヒントにしますが,ここで注意しなければならないのは,この言葉がアプリケーションの下に置かれていることで,私は最初から知らなかったので,場所を間違えて,多くの時間を浪費したことです
<?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>