写下下一个测试:
private val mockContext = Mockito.mock(Context::class.java)
private val notificationManager = Mockito.mock(NotificationManager::class.java)
@RequiresApi(Build.VERSION_CODES.O)
@Test
@Throws(Exception::class)
fun clearNotificationsTest() {
Mockito.`when`(mockContext.getSystemService(Context.NOTIFICATION_SERVICE)).thenReturn(notificationManager)
val captor: ArgumentCaptor<NotificationChannel> = ArgumentCaptor.forClass(NotificationChannel::class.java)
mockContext.registerNotificationChannels()
Mockito.verify(notificationManager.createNotificationChannel(captor.capture()))
val argument: NotificationChannel = captor.value
assertThat(argument.id, equalTo(CHANNEL_ID))
assertThat(argument.name.toString(), equalTo(CHANNEL_NAME))
assertThat(argument.importance, equalTo(NotificationManagerCompat.IMPORTANCE_HIGH))
}
并在我的verify
中获取下一个错误:
org.mockito.exceptions.misusing.notamockexception: 传递到verify((的参数是类型单元,不是模拟! 确保正确放置括号! 请参阅正确验证的示例: 验证(模拟(.someMethod((; 验证(模拟,时间(10((。somemethod((; 验证(模拟,atleastonce(((。somemethod((;
这就是您使用模拟
编写验证的方式Mockito.verify(notificationManager).createNotificationChannel(captor.capture()));
您如何定义
notificationManager
使用模拟声道,您可以在测试中定义一个字段
中的以下内容@Mock
NotificationManager notificationManager
@Before
public void setup()
{
MockitoAnnotations.init(this);
}
注意:要在类上监视它,必须是模拟或 real 对象已被监视的对象。即
val notificationManagerSpy: spy(notificationManager)
如果您使用的是诸如Robolectric之类的测试框架,则将具有 real ShadownotificationManager,因此您应该监视真实对象。解决方案将如下:
@RequiresApi(Build.VERSION_CODES.O)
@Test
@Throws(Exception::class)
fun clearNotificationsTest()
{
val notificationManagerSpy: spy(notificationManager)
Mockito.`when`(mockContext.getSystemService(Context.NOTIFICATION_SERVICE))
.thenReturn(notificationManagerSpy)
val captor: ArgumentCaptor<NotificationChannel> =
ArgumentCaptor.forClass(NotificationChannel::class.java)
mockContext.registerNotificationChannels()
Mockito.verify(notificationManagerSpy
.createNotificationChannel(captor.capture()))
val argument: NotificationChannel = captor.value
assertThat(argument.id, equalTo(CHANNEL_ID))
assertThat(argument.name.toString(), equalTo(CHANNEL_NAME))
assertThat(argument.importance,
equalTo(NotificationManagerCompat.IMPORTANCE_HIGH))
请参阅:https://www.baeldung.com/mockito-spy有关间谍的更多信息以及什么是有效的可间谍对象。