简体   繁体   English

模拟返回错误的集合

[英]Mock returns Wrong Collection

I want to return a filled Map with my mocked Object, but the size of the Map is always Null.我想用我的模拟对象返回一个填充的 Map,但 Map 的大小始终为 Null。 The mocked Object "CommandLineValues options" is not Null and also the Boolean variable "doCleanFirst" I can mock successfully.模拟的对象“CommandLineValues 选项”不是 Null,我也可以成功模拟布尔变量“doCleanFirst”。

Here is my Testclass:这是我的测试类:

@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();
    }
}

Here is the constructor of my class where the code start, the tested Method is not relevant:这是代码开始的我的类的构造函数,测试方法不相关:

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

I also tried other variants:我还尝试了其他变体:

  1. Mock the Map and the return value of the method "isEmpty"模拟 Map 和方法“isEmpty”的返回值
  2. Initialize the Testclass and give the mocked Object to the constructor初始化测试类并将模拟的对象提供给构造函数

But the whiteList has always the size = 0但是 whiteList 的大小总是 = 0

在此处输入图片说明

Thx, this works now: 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();
    }

First I mock the methods which will be executed in the contructor and then I create the instance of my testclass.首先我模拟将在构造函数中执行的方法,然后我创建我的测试类的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM