2

I am trying to write Junit for a simple method that takes filename as input and returns the byte array as output. The difficulty I am facing is that the file will not be available while running Junit. So, how can I test this method? I see two options:

  • somehow make the file available for Junit (I am not sure if this is possible).
  • Mock/stub the behavior.

I am pasting the code of the method below:

public byte[] readFileAndReturnBytes(String filePath) throws IOException {
    InputStream is = null;
    File file = null;
    byte[] fileBytes = null;
    try
    {
        file = new File(filePath);
        is = new FileInputStream(file);
        fileBytes = IOUtils.toByteArray(is);
    }
    catch(IOException e){
        throw e;
    }
    finally{
        if(is != null)
        {
            is.close();
            file = null;
        }
    }
    return fileBytes;
}

I am using Mockito for mocking. Does anyone have any ideas?

Sampada
  • 2,931
  • 7
  • 27
  • 39
Maruthi Podila
  • 67
  • 1
  • 14
  • 1
    you can use before/after class annotations to create/delete a small local file before/after test execution... I can write an answer showing that, but it's pretty trivial... Let me know... – Palcente Apr 21 '16 at 12:09
  • 1
    As Palcente suggested: Use temporary files for testing. Have a look at JUnit's TemporaryFolder. http://junit.org/junit4/javadoc/latest/org/junit/rules/TemporaryFolder.html – Roland Weisleder Apr 21 '16 at 12:11
  • The error here is that you should not use Junit on any of the above. When you are using an external library you should rely that its methods would behave correctly. Only mock your classes and their dependency. In the case above, you would mock the readFile... method to return an expected value using mockito. – LoreV Apr 21 '16 at 12:23
  • This question seems similar to [this other one](http://stackoverflow.com/q/17681708/1426891). Does it provide any insight into testing strategies with files? – Jeff Bowman Apr 21 '16 at 22:40
  • I have created a Junit's TemporaryFolder Rule and it did the trick. Thank you all for the help! – Maruthi Podila Apr 22 '16 at 07:46
  • please consider using this common method: Files.readAllBytes(Path path). avoid re-inventing the wheel -- you have errors in the your implementation! – shlomi33 Apr 25 '16 at 17:59
  • I am writing unit test cases for code written by someone else. I can not change the implementation at this point. Thank you for the feedback. – Maruthi Podila Apr 26 '16 at 11:32

1 Answers1

0

For me the best option here is to refactor your method so that it receives File not String filePath. In this case you can mock your file and call the method readFileAndReturnBytes(mockedFile).

File mockedFile = mock(File.class);
testClass.readFileAndReturnBytes(mockedFile);

If you don't want to refactor you code, I suggest you to check JUnit TempopratyFolder.

Sergii Bishyr
  • 8,331
  • 6
  • 40
  • 69