1

I just started to write Unit tests for Android code and got stuck.

Writing test for this peace of code:

Intent intent = new Intent(context, Some.class);
intent.setAction(Some.SYNC_SERVICE_ACTION_SYNC);
context.startService(intent);

And I would like to know how using mockito I can get intent action to test class for comparison if there was called the same intent?

In the test I'm trying to do something like this:

String action = "SyncService.SYNC_SERVICE_ACTION_SYNC";
when(context.startService(any())).thenReturn(Intent);
assertEquals("Do not match", action, Intent.getAction());

Maybe someone can help?

Jovani
  • 11
  • 3

1 Answers1

0

I found an answer to my question and to get info about intent in your class from mockito test you should do like:

ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
doReturn(null).when(context.startService(any()));
verify(context).startService(captor.capture());

String intentAction = captor.getValue().getAction();

I hope it will help someone! Cheers!

UPDATED

For some reason cant use

doReturn(null).when(context.startService(any()));

Instead use:

when(context.startService(any())).thenReturn(null);
Jovani
  • 11
  • 3
  • A) you should prefer when/thenReturn anyway (see [here](https://stackoverflow.com/questions/20353846/mockito-difference-between-doreturn-and-when) on why) and B) when using doReturn, it goes like this: `doReturn(x).when(mock).foo()` - you only put the mock object into `when()` . Beyond that: the **default** for a mock object is to return **null**. There is **no** point in telling mockito to do that. You only tell it when something else but null needs to be returned! – GhostCat Aug 31 '17 at 07:24
  • @GhostCat Thank you for your comment, after reading the simple explanation about these different stubs, made my understanding much clearer. – Jovani Aug 31 '17 at 07:52