10

I got below code in a method which I want to test

File f = map.get("key1")
BuffereReader r = new BufferedReader(new FileReader(f));
String line=null;
do {
    line=r.readLine();
} while(r!=null);

I want to mock this operation so that I can pass the content of the file from the JUnit test case. I have done below:

Map fles = Mockito.mock(ConcurrentHashMap.class);
File file = Mockito.mock(File.class);
Mockito.when(files.get("key1")).thenReturn(file);

FileReader fileReader = Mockito.mock(FileReader.class);
BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);

try {
     PowerMockito.whenNew(FileReader.class).withArguments(file).thenReturn(fileReader);
     PowerMockito.whenNew(BufferedReader.class).withArguments(fileReader).thenReturn(bufferedReader);
     PowerMockito.when(bufferedReader.readLine()).thenReturn("line1")
         .thenReturn("line2").thenReturn("line3");

    } catch (Exception e) {
        Assert.fail();
    }

So basically I need to pass "line1", "line2" and "line3" as lines from the file which are read by the mocked BufferedReader.

However upon doing that, it failes as NullPointerException when trying to instantiate new FileReader(f) part.

So is it because I can't mock a BufferedReader or the approach is wrong?

Thanks

Dinesh
  • 2,194
  • 3
  • 30
  • 52
user2654241
  • 167
  • 1
  • 2
  • 13

2 Answers2

14

You could extract a method for doing the actual reading and then test that instead. That would mean you only have to mock a single reader. For example, your code would be something like this:

public void aMethod(){
    File f = map.get("key1")
    BuffereReader r = new BufferedReader(new FileReader(f));
    readStuff(r);
}

public void readStuff(BufferedReader r){
    String line=null;
    do {
        line=r.readLine();
    } while(r!=null);
}

then your test code would be more like the following:

BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
Mockito.when(bufferedReader.readLine()).thenReturn("line1", "line2", "line3");
objUnderTest.readStuff(bufferedReader);
//verify result
Bobbo
  • 305
  • 1
  • 7
  • 11
    +1 to rewriting the test, but at that point you don't even need to mock the BufferedReader; you can skip straight to `new BufferedReader(new StringReader("line1\nline2\nline3"))`. – Jeff Bowman Sep 24 '13 at 20:39
0

You can try PowerMock annotations. Check this : https://code.google.com/p/powermock/wiki/MockConstructor

Sai
  • 376
  • 7
  • 18
  • I am using PowerMockito and PowerMock is not available to me. So any answers in context of PowerMockito will be very useful. – user2654241 Sep 24 '13 at 09:29
  • Check this link: http://stackoverflow.com/questions/7523389/how-do-i-use-powermockito-to-mock-the-construction-of-new-objects-when-testing-a – Sai Sep 24 '13 at 11:10