dimanche 1 novembre 2015

Mocking Android services using Mockito

I have a service which is started when my app starts, and then different activities can bound to the service for different operations, and then unbound when done.

To write a unit test for one of the activities that uses this service, I needed to mock the service's IBinder instance, and make the binder object return different values. I tried different methods, but none of them could make the activity to use the mocked binder.

First, I mocked both service and binder, and made mock service return mock binder, but obviously as the activity tries to connect to the real service, it also gets the real binder.

Then I started the real service in my test, used reflection to replace the real binder instance (which service returns to clicks during onBind) with mock instance, and then started the activity under test, but still somehow the activity was getting the real binder!

Any idea how I can do this? Is this the right way even to test activities which bound to a service? or should I use a completely different approach.

I also found this blog post where the author explains exactly what I needed, but he is using Robolectric. Is this the only way to do such testing?

Thanks

Aucun commentaire:

Enregistrer un commentaire