无法验证Mockito中的捕获者

时间:2019-06-27 12:24:13

标签: android mockito verify

编写下一个测试:

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()的参数是Unit类型的,不是模拟的!   确保正确放置括号!   请参阅正确验证的示例:   verify(mock).someMethod();   verify(mock,times(10))。someMethod();   verify(mock,atLeastOnce())。someMethod();

2 个答案:

答案 0 :(得分:1)

这是您使用模拟编写验证的方式

Mockito.verify(notificationManager).createNotificationChannel(captor.capture()));

答案 1 :(得分:0)

您如何定义

notificationManager

使用MockitoAnnotations,您可以在测试中定义以下字段

@Mock
NotificationManager notificationManager

@Before
public void setup()
{
   MockitoAnnotations.init(this);
}

注意::要监视类,它必须是模拟对象或被监视的真实对象。即

  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,了解有关间谍以及什么是有效的间谍对象的更多信息。