Shubham
Shubham

Reputation: 75

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().

Upvotes: 1

Views: 125

Answers (1)

Andy Turner
Andy Turner

Reputation: 140329

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.

Upvotes: 1

Related Questions