Monday, April 26, 2010

Adding Unit Tests to an Existing Android Project

I looked for tutorials on how to add Unit Testing to an existing Android Project, but wasn't able to find anything too recent or complete. There is probably more than one way to do this, hopefully you'll find mine useful. This applies to Android 2.1 using Eclipse 1.2.2.20100216-1730.

I performed the following steps in the same workspace as the project I wished to write Unit Tests for.

1. File::new::Project...

2. Select Android::Android Test Project.

3. Click Next.

4. Name the test project, Select the project you want to write tests against with the "An existing Android Project" field (use the browse button).

5. Click Finish.

6. In the test project you just created, create a new source file with File::New::JUnit Test Case.

7. In the dialog, select "New JUnit 3 test", the source folder should correspond to the new test project you just created. The package should be the test package of the new project. Name the class as you wish (e.g. FooTest). For "Class Under Test" you can browser and pick a class from the project you wish to test.

8. In the new test class you created, create a JUnit test method. The name of the test method needs to start with "test" (e.g. testFooBar). You can use junit.framework.Assert methods to test the conditions you expect.

9. Run the test cases by clicking Run::Run as::Android JUnit Test.

10. The test results will appear in a JUnit perspective on the left side.

Am I missing any steps? Have I missed any nuance or a better way to do it? Help me out and comment below.