jeudi 5 mars 2015

RecyclerView Adapter in unit test

How to test support library classes when running unit tests in Android Studio? According to the introduction on http://ift.tt/1KkPIk8 it works with the default Android classes:



Unit tests run on a local JVM on your development machine. Our gradle plugin will compile source code found in src/test/java and execute it using the usual Gradle testing mechanisms. At runtime, tests will be executed against a modified version of android.jar where all final modifiers have been stripped off. This lets you use popular mocking libraries, like Mockito.



However, when I try to use Mockito on a RecyclerView adapter like so:



@Before
public void setUp() throws Exception {
adapter = mock(MyAdapterAdapter.class);
when(adapter.hasStableIds()).thenReturn(true);
}


Then I will receive the error message:



org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public.
It is a limitation of the mock engine.


The reason is that the support library does not provide such a jar file "where all final modifiers have been stripped off".


How do you test it then? By subclassing & overriding the final methods perhaps (which doesn't work so, NO). Perhaps PowerMock?


Aucun commentaire:

Enregistrer un commentaire