是否可以在测试用例中使用 Mockito return 清空 LinkedHashMap 列表

Is it possible to return empty list of LinkedHashMap using Mockito in a test case

我正在编写一个单元测试,它访问 App class 中 LinkedHashMap 的 public 变量。我想将其模拟为 return 空列表,请问我该怎么做

应用有这个变量

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

单元测试需要 mapOfQCC 到 return 空列表

我试过了,没用

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);

提前致谢 R

LinkedHashMap<String, ArrayList<QCCheck>> keepOldIfNeed = app.mapOfQCC; // keep the list in object if you need 
app.mapOfQCC = new LinkedHashMap<>(); // this is empty

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

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

Mockito 做不到这一点。 您只能存根方法调用。

您有 2 个选择:

  • 为您的字段提供 getter(并可能将字段设为私有)。存根 getter.
  • 在测试中设置字段。是public。没有什么能阻止你这样做。