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 problem is that you are creating a mock which in the end is a local variable inside the @Before
method.
When you later run your tests this variable is not accessible anymore, nor there is any notion of a global mock for a class (at least in vanilla Mockito).
So either use a global variable which you then initialize manually in the setUp method:
private NotificationCompat.Builder notificationBuilder;
@Before
public void setUp() {
notificationBuilder = Mockito.mock(NotificationCompat.Builder.class);
}
or use Mockito annotations:
@Mock
private NotificationCompat.Builder notificationBuilder;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
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);
}
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.