简体   繁体   English

使用 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();

The above code is part of a function returning void, I'm able to mock Resource and ResourceLoader but not able to find a way to mock BufferedReader.上面的代码是 function 返回 void 的一部分,我可以模拟 Resource 和 ResourceLoader 但无法找到模拟 BufferedReader 的方法。 I also want to mock the List and call Mockito.verify() on List.add().我还想模拟 List 并在 List.add() 上调用 Mockito.verify()。

If the list is local to the method, there is no side effect for you to test.如果该列表是该方法的本地列表,则您无需测试任何副作用。 Then again, there is no obvious purpose to using this method in non-test code either, because you'd read the data into the list, and then discard it.再说一次,在非测试代码中使用此方法也没有明显的目的,因为您会将数据读入列表中,然后将其丢弃。

You would need to inject the list as a parameter to the method:您需要将列表作为参数注入方法:

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

And you can now test this by invoking yourMethod in your test, with a List parameter, that you can inspect afterwards.现在,您可以通过在测试中调用yourMethod并使用List参数来测试它,您可以在之后进行检查。

I also want to mock the List and call Mockito.verify() on List.add().我还想模拟 List 并在 List.add() 上调用 Mockito.verify()。

There is essentially no need to mock a List , especially for this purpose: inject a list, a regular ArrayList , and just check that the list has grown by 1 after the method call.基本上不需要模拟 List ,特别是为此目的:注入一个列表,一个常规的ArrayList ,并在方法调用后检查列表是否增长了 1。

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

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