使用 Mockito 对以下代码进行单元测试

Unit tests for following code with Mockito

List<String> lineArray = new ArrayList<String>();
Resource resource = resourceLoader.getResource("classpath:abc.txt");
InputStream in = resource.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
    if(line.startsWith("#")) {
        lineArray.add(reader.readLine());           }
}
reader.close();

以上代码是返回 void 的函数的一部分,我可以模拟 Resource 和 ResourceLoader,但无法找到模拟 BufferedReader 的方法。我还想模拟列表并在 List.add() 上调用 Mockito.verify()。

如果列表是方法本地的,则没有副作用供您测试。话又说回来,在非测试代码中使用此方法也没有明显的目的,因为您会将数据读入列表,然后将其丢弃。

您需要将列表作为参数注入方法:

void yourMethod(List<String> lineArray) {
  Resource resource = resourceLoader.getResource("classpath:abc.txt");
  // ... etc.
}

您现在可以通过在测试中调用 yourMethod 来测试它,使用 List 参数,之后您可以检查该参数。

I also want to mock the List and call Mockito.verify() on List.add().

基本上没有必要模拟一个列表,特别是为了这个目的:注入一个列表,一个常规的ArrayList,然后检查列表是否已经增长在方法调用后增加 1。