Unit test your application

WonderCsabo edited this page Dec 8, 2014 · 6 revisions

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 = Robolectric.setupActivity(MyActivity_.class);   
	// onCreate is called, myDependency gets injected 

	// 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 the getInstance_() method of MyImplementation_ 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.

21/10/2018 The 4.5.2 release is out !

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Extending AndroidAnnotations

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.