Saturday, June 25, 2011

JUnit testing with Android

Just a short note for those of us who are familiar with writing unit tests in normal Java environments (i.e. not Android's dalvik):

Do not import any unit test methods or classes.

The libraries will not be available at runtime on the device and you will get NoClassDefFoundErrors for everything from Assert to hamcrest Matchers. It's reflex to type "import static org.hamcrest...." or "import static org.junit...." etc at the top of your test fixture class, but resist the habit when developing for Android.

Just extend ActivityInstrumentationTestCase2 and call the assertion methods that you inherit, like so:
assertTrue(message, condition);
Note that it's not Assert.assertTrue().

Aside from that, following Google's Hello Testing guide will work without gotchas.

Friday, June 17, 2011

Hamcrest imports

I'm putting this down in writing because I keep getting asked. What are those static imports from hamcrest? You know, the ones that we always use?

import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;