I have created a test for Notifications in Android and am struggling with making Mock objects. When I try to Mock the notificationBuilder
following this post(which suggests wrapping Android notifications in a custom class) I get a null notificationBuilder
, which then ruins my tests.
My minimal code showing this is:
@Before
public void setUp() {
NotificationCompat.Builder notificationBuilder = Mockito.mock(NotificationCompat.Builder.class, Mockito.RETURNS_SELF);
}
where notificationBuilder is null. How can I get a Mock NotificationCompat.Builder as the return value? I thought this was what RETURNS_SELF
was supposed to do.
With a null value I can't use my Builder as part of a when().then() for further testing.
The Mockito.mock(...)
is returning null
because you aren't mocking anything. You need to declare a global variable with the @Mock
annotation and initialize your mock object in the setUp()
method(you can call this anything as long as it has the @Before
annotation on it). Try the below code snippet.
@Mock
NotificationCompat.Builder notificationBuilder;
@Before
public void setUp(){
notificationBuilder = Mockito.mock(NotificationCompat.Builder
.class);
}
@Test
public void testSharedPrefInjection(){
assertNotNull(notificationBuilder);
}