简体   繁体   English

如何编写测试用例readFile方法(返回类型为void)

[英]How to write test case readFile method which return type is void

I am new in writing test cases, Please help me for writing test case for below methods . 我是编写测试用例的新手,请帮助我为以下方法编写测试用例。 Thanks in advance!! 提前致谢!!

public void readFile() throws IOException{
  linesProcessed = 0;
  FileInputStream fileInStream = new FileInputStream(filePath);
  DataInputStream dataInStream = new DataInputStream(fileInStream);
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInStream));
  String strLine;

  fileData.clear();
  while(StringUtils.isNotBlank((strLine = bufferedReader.readLine()))) {
    ++linesProcessed;
    processLine(strLine);
  }
  bufferedReader.close();
  dataInStream.close();
  fileInStream.close();         
}

Many things to say here. 这里有很多要说的。

First of all, to answer your question. 首先,回答您的问题。 When a method doesn't return something, you can still can check whether some "other state" gets updated accordingly. 当某个方法不返回任何内容时,您仍然可以检查某个“其他状态”是否得到相应更新。

In your case, one meaningful point of observation could be that call 在您的情况下,一个有意义的观察点可能是该调用

processLine(strLine);

In other words: you could see what that method is doing, and somehow verify that the other method was called as you would expect it. 换句话说:您可以看到该方法在做什么,并以某种方式验证是否已调用另一个方法。

Then: you actually wrote hard-to-test code. 然后:您实际上编写了难以测试的代码。 One reason for that is because this method starts its work on a string (that points to a file). 其原因之一是因为此方法在字符串 (指向文件)上开始工作。 Instead, you could pass a reader object to that method already. 相反,您可以将阅读器对象传递给该方法。 Then there wouldn't be a need to use PowerMock for example. 这样就不需要使用PowerMock了。 You simply prepare a reader object that has known content, and then you can verify that actions follow that match that prepared content! 您只需准备一个具有已知内容的阅读器对象,然后就可以验证所执行的操作与该准备好的内容相匹配!

Beyond that, you should learn about try-with-resources, and you should also study more how to do IO. 除此之外,您还应该了解尝试资源的知识,还应该学习更多有关如何进行IO的知识。 There is no point in closing all 3 streams. 关闭所有3个流没有意义。 When you create a reader on some other stream, and you close the outer reader, that "base" stream gets closed automatically along the way. 当您在其他流上创建读取器并关闭外部读取器时,该“基本”流将自动关闭。

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

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