views:

171

answers:

2

I'm developing Android application using third party libraries (Twitter4j). I want to be able mock those objects (also objects created by me) in JUnit and functional tests.

Do you have any good experiences using some mocking libraries and you can recommend them?

A: 

Android Mock is written on top of EasyMock 2.4 which is well-known mock framework for Java

DixonD
Do you have any experience using it? What are pros and cons of using it?
pixel
We also found that project a while ago, but it doesn't look very active... I'd rather not rely on a pre-alpha release of something I use to verify my app's behaviour.
Matthias
+6  A: 

Except for android-mock mentioned by DixonD (which is a fairly young, unproven library), there currently is no solution. You can immediately forget anything based on CGLib (Mockito, plain EasyMock), since CGLib relies on byte code generation and won't work on Dalvik (it also relies on the Java Beans package, which is also not part of Android).

For what it's worth, you could use the very few mock classes coming with Android (like MockContext), but they don't verify behavior, they're just stubs. Their default behavior is to throw a runtime error in every method, so you have to subclass them and override the methods you want to mock.

However, you can still use mocking libraries in non-instrumentation tests, i.e. in your standard unit tests executed on the JVM. You can use PowerMock to mock framework methods, it has support for mocking static methods and constructors, making the mocking as powerful as e.g. in Ruby (just more painful to use).

We use JUnit 4 + PowerMock + Mockito and mock out classes like Context and TextUtils in a base class from which we inherit every normal JUnit test. For instrumentation tests, we create custom mock classes and decide using a factory which implementation (mock or not) to instantiate at runtime.

Matthias
You've written that you use Mockito to mock Context - how you are doing that contrary to your first paragraph (that it can't be run because it relies on CGLib)
pixel
We distinguish between tests running on the JVM and instrumentation (UI unit and story tests) which run on the emulator (i.e. the Dalvik VM). For instance, our API connector has a dependency on a Context, but the unit test for that class is not executed on the emulator, so we can mock out the Context using Mockito and Powermock. Anything that involves running an Activity though has to be run on the emulator, where these libraries won't work.
Matthias
I've updated the last paragraph to clarify our approach to this.
Matthias