首页 > 解决方案 > 模拟返回错误的集合

问题描述

我想用我的模拟对象返回一个填充的地图,但地图的大小总是空的。模拟的对象“CommandLineValues options”不是 Null,而且我可以成功模拟的布尔变量“doCleanFirst”。

这是我的测试类:

@RunWith(MockitoJUnitRunner.class)
public class IndexBMECatTest {

    @InjectMocks
    private IndexBMECat classUnderTest;

    @Mock
    private CommandLineValues options;

    @Test
    public void testAccessoryItemHasNoDublicates() {

        Map<String, String> testMap = new HashMap<>();
        testMap.put("key", "value");

        when(options.getCleanFirst()).thenReturn(false);
        when(options.readWhitlist()).thenReturn(testMap);
        
        classUnderTest.run();
    }
}

这是我的代码开始的类的构造函数,测试的方法不相关:

private boolean doCleanFirst;
private Map<String, String> whiteList;

public IndexBMECat(TransportClient client, CommandLineValues options, BMECatReader reader) throws Exception {
             
        this.doCleanFirst = options.getCleanFirst();
        this.whiteList = options.readWhitlist();
      
        if (whiteList.isEmpty()) {
            throw new Exception("Missing whiteList");
        }
    }

我还尝试了其他变体:

  1. 模拟地图和方法“isEmpty”的返回值
  2. 初始化 Testclass 并将模拟的 Object 交给构造函数

但是白名单的大小总是= 0

在此处输入图像描述

标签: javajunitcollectionsmockito

解决方案


Thx,这现在有效:

private IndexBMECat classUnderTest;

    @Mock
    private CommandLineValues options;

    @Mock
    private BMECatReader reader;

    @Mock
    TransportClient client;

    @Before
    public void setUp() throws Exception {
        Map<String, String> testMap = new HashMap<>();
        testMap.put("key", "value");
        when(options.getCleanFirst()).thenReturn(false);
        when(options.readWhitlist()).thenReturn(testMap);
        classUnderTest = new IndexBMECat(client, options, reader);
    }

    @Test
    public void testAccessoryItemHasNoDublicates() {

        classUnderTest.run();
    }

首先,我模拟将在构造函数中执行的方法,然后创建我的测试类的实例。


推荐阅读