Unit test your application - PerfectCarl/androidannotations GitHub Wiki
You should start by reading the Testing chapter in the Android documentation.
You may run your tests on a real environment, such as an emulator or a device. However, if you need fast running tests, you should definitely have a look at Robolectric an out-of-container test frameworks that runs within JUnit. It is absolutely needed if you use a continuous test runner, such as infinitest.
For instrumentation / integration tests, have a look at Robotium.
At first, you may find it hard to unit test your components written using AndroidAnnotations. Here are a few key points that should help you:
- The usual way to unit test a component that has dependencies is to replace its dependencies with dummy, fake, stub or mock objects.
- There's no way to tell AndroidAnnotations that you want to inject mocks instead of real objects, because it works at compile time, so the code must always be production ready.
- You should test the generated classes (e.g.
MyActivity_
), not the annotated ones (e.g.MyActivity
). The annotations are adding behavior to your code, so you shouldn't test it as if there were no annotation. - Test your activities behavior, not AndroidAnnotations' behavior. The framework already has tests of its own to check that the annotations work correctly.
- You can let AndroidAnnotations dependency injection take place, and then reinject the mocked dependency. The fields have at least default scope, which mean they can be accessed from the same package, so you'd have to create the test in the same package as the activity:
MyActivity_ activity = new MyActivity_();
// myDependency gets injected
activity.onCreate(null);
// you reinject myDependency
activity.myDependency = Mockito.mock(MyDependency.class);
- In AndroidAnnotations, dependencies are injected by calling
MyImplementation_.getInstance_()
. You could use runtime bytecode manipulation with a tool such as PowerMock to let thegetInstance_()
method ofMyImplementation_
return a mock. This might require some initial work though, because you'd have to mix PowerMock test runner and Robolectric test runner. Also, this wouldn't run on Dalvik.