3

Our normal way of writing unit tests is using mocks via Mockito. However, LocalBroadcastManager, for some unexplicable reason, is final - thus preventing Mockito from expanding it, which prevents us to mock/spy it...

--> How can I write unit tests for a class that contain LocalBroadcastManager?

I would for example like to check that when some conditions occur etc. certain broadcasts (containing specific extras) are sent out.

fgysin
  • 11,329
  • 13
  • 61
  • 94

1 Answers1

1

Use PowerMock:

Run your test class with PowerMock:

@RunWith(PowerMockRunner.class) 
@PrepareForTest({LocalBroadcastManager.class})

Then where-ever in your test you want to mock the static method, do this:

    PowerMockito.mockStatic(LocalBroadcastManager.class);
    LocalBroadcastManager instance = mock(LocalBroadcastManager.class);
PowerMockito.when(LocalBroadcastManager.getInstance(context)).thenReturn(instance);
LoveForDroid
  • 1,072
  • 12
  • 25
  • It trows me an error when I call PowerMockito.mockStatic(LocalBroadcastManager.class): Cannot subclass final class class android.support.v4.content.LocalBroadcastManager – Víctor García Dec 12 '18 at 18:40
  • 1
    Make sure you do this on top of your class: @RunWith(PowerMockRunner.class) @PrepareForTest({LocalBroadcastManager.class}) – LoveForDroid Dec 12 '18 at 19:23
  • That worked :D Could you update the answer to make it more clear for others? Thank you! – Víctor García Dec 12 '18 at 19:30