Cliff
Cliff

Reputation: 11238

Regular JUnit in an Android project

I've been trying to figure out how to include standard JUnit 3.x (or even JUnit4.x) tests in my Android applications. I want to use JUnit over the Android unit test tools because it is faster and runs directly in my IDE (where the Android JUnit tools need to be deployed to the device or emulator 1st). I also want to use JUnit to impose proper SoC (Separation of Concerns). Originally I had set up multiple modules to allow for this, the Main Android module and a core library module where the main module would have all of the Android specifics and the core module would have Plain Old Java Objects (POJOs) and JUnit goodness.

Recently I started working on an Android project where I developed a library to handle some low level android specific work and expose it as high level operations to the main module. The problem is that I need to use JUnit in the library module but I don't want to break out yet another module to do so. In an ideal world I would have:

Main module: includes all the high level UI and controller logic to navigate between activities, fragments, etc. Depends on MyLib.

MyLib: Contains high level interfaces wrapping low level logic to handle things such as android specific networking, persistence, accelerometer reads, etc. Lots of POJOs involved in some of the low level logic. Also includes an example or demo app to exercise these interfaces directly. Includes the ability to run JUnit on the POJOs.

Am I living a pipe dream or is there a way to intelligently set this up using current development tools? I use IntelliJ Idea primarily but would be open to an Eclipse specific solution as well.

Upvotes: 1

Views: 303

Answers (2)

Siddharth
Siddharth

Reputation: 9574

In short

  • Use Junit for testing classes and static methods.
  • Use Instrumentation to test the click-ux response of your app

Instrumentation is a pain to get started, takes time to learn. So invest time in hello worlds a lot. Its a whole new world.

Upvotes: 0

EJK
EJK

Reputation: 12527

The problem you will run into with running your tests directly in the JUnit test runner is that you will not be able to call any com.android.* classes. That is because these classes, in android.jar, are stubbed out in your SDK. Only the Dalvik- byte code versions of these have actual implementations those only run in the emulator.

Avoiding calls into com.android.* classes is very difficult, especially given that so many Android methods require a Context.

I too find this a bit frustrating because the emulator is slow to launch and slow to execute code. It makes test development very tedious.

The only luck I have had using the JUnit test runner w/out the emulator is to create a separate, non-Android project that points at my project files. This allowed my to launch JUnits outside of the emulator, however I was very limited in what classes I could actually test.

Upvotes: 2

Related Questions