简体   繁体   中英

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. I also want to mock the List and call Mockito.verify() on List.add().

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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