简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM