【问题标题】:Is it possible to return empty list of LinkedHashMap using Mockito in a test case是否可以在测试用例中使用 Mockito 返回 LinkedHashMap 的空列表
【发布时间】:2020-07-17 13:08:54
【问题描述】:

我正在编写一个单元测试,它访问 App 类中 LinkedHashMap 的公共变量。我想模拟这个返回空列表,请问我该怎么做

App 有这个变量

  public LinkedHashMap<String, ArrayList<QCCheck>> mapOfQCC =
        new LinkedHashMap<>();

单元测试需要mapOfQCC返回空列表

我试过了,没用

every(app.mapOfQCC).thenReturn(LinkedHashMap<String, ArrayList<QCCheck>>())

错误

when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

提前致谢 回复

【问题讨论】:

    标签: java android unit-testing mockito


    【解决方案1】:

    错误消息是不言自明的。 您正在尝试存根字段访问:

    every(app.mapOfQCC).thenReturn(LinkedHashMap<String, ArrayList<QCCheck>>())
    

    这在 Mockito 中是不可能的。 您只能存根方法调用。

    你有两个选择:

    • 为您的字段提供一个吸气剂(并可能将字段设为私有)。存根 getter。
    • 在您的测试中设置字段。它是公开的。没有什么能阻止你这样做。

    【讨论】:

      【解决方案2】:
      LinkedHashMap<String, ArrayList<QCCheck>> keepOldIfNeed = app.mapOfQCC; // keep the list in object if you need 
      app.mapOfQCC = new LinkedHashMap<>(); // this is empty
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-30
        • 2013-02-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多