This is a duplicate of this question. There are bunch of similar questions/answers as well but none helped me. As there are hundreds of developers accepted some answers I am probably wrong somewhere and have no idea where is my problem!
This is my sample class and I want to test its method.
final class NavigationBuilder {
@VisibleForTesting List<Intent> mIntentList = new ArrayList<>(5);
@VisibleForTesting
void addNextScreenBasedOnBookingStatus(final Booking booking) {
final ChatMsgDbAsyncHelper helper = new ChatMsgDbAsyncHelper();
if (booking == null) {
helper.cleanAllMessages(mContext); // <= Crash here
}
}
}
This is my test class:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ChatMsgDbAsyncHelper.class, SplashActivity.class})
public class NavigationBuilderTest {
private SplashActivity mActivity;
private NavigationBuilder mNavBuilder;
@Before
public void setUp() throws Exception {
mActivity = new SplashActivity();
ISplashView view = mock(ISplashView.class);
PassengerStorage passengerStorage = mock(PassengerStorage.class);
mNavBuilder = new NavigationBuilder(mActivity, view, passengerStorage);
}
@Test
public void addNextScreenBasedOnBookingStatus_whenBookingIsNull() throws Exception {
ChatMsgDbAsyncHelper spy = PowerMockito.spy(new ChatMsgDbAsyncHelper());
PowerMockito.doNothing().when(spy).cleanAllMessages(mActivity);
mNavBuilder.addNextScreenBasedOnBookingStatus(null);
assertTrue(mNavBuilder.mIntentList.isEmpty());
}
}
Test fails and the reason is NullPointerException
because test is running logic inside of helper.cleanAllMessages(mContext);
. My expectation from above mock is those logic should not be performed.
Caused by: java.lang.NullPointerException at com.xxx.xxx.db.entities.ChatMessageTable.(ChatMessageTable.java:23)