【问题标题】:What's the way to get Intent information with unit test from class method?从类方法中通过单元测试获取 Intent 信息的方法是什么?
【发布时间】:2017-08-30 18:40:36
【问题描述】:

我刚开始为 Android 代码编写单元测试,结果卡住了。

为这种和平的代码编写测试:

Intent intent = new Intent(context, Some.class);
intent.setAction(Some.SYNC_SERVICE_ACTION_SYNC);
context.startService(intent);

我想知道如何使用 mockito 获得意图操作来测试类以进行比较,如果有相同的意图被调用?

在测试中我正在尝试做这样的事情:

String action = "SyncService.SYNC_SERVICE_ACTION_SYNC";
when(context.startService(any())).thenReturn(Intent);
assertEquals("Do not match", action, Intent.getAction());

也许有人可以帮忙?

【问题讨论】:

    标签: android unit-testing junit mockito


    【解决方案1】:

    我找到了我的问题的答案,并从 mockito 测试中获取有关您班级中意图的信息,您应该这样做:

    ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
    doReturn(null).when(context.startService(any()));
    verify(context).startService(captor.capture());
    
    String intentAction = captor.getValue().getAction();
    

    我希望它会帮助别人!干杯!

    更新

    由于某种原因无法使用

    doReturn(null).when(context.startService(any()));
    

    改为使用:

    when(context.startService(any())).thenReturn(null);
    

    【讨论】:

    • A) 你应该更喜欢 when/thenReturn (请参阅here 了解原因)和 B) 当使用 doReturn 时,它是这样的:doReturn(x).when(mock).foo() - 你只将模拟对象放入 @987654326 @ .除此之外:模拟对象的默认是返回null。告诉 mockito 这样做是没有意义的。您只在需要返回除 null 之外的其他内容时才告诉它!
    • @GhostCat 感谢您的评论,在阅读了关于这些不同存根的简单说明后,我的理解更加清晰了。
    猜你喜欢
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多