Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write unit tests for classes using LocalBroadcastManager?

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.

like image 439
fgysin Avatar asked Dec 19 '25 22:12

fgysin


1 Answers

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);
like image 136
LoveForDroid Avatar answered Dec 21 '25 15:12

LoveForDroid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!