0

I'm trying to test code which is inside a try-catch statement such as:

@Service
public class DoSomething {

  public void uploadFile(String filename) {
   try{
    File file = new File(filename + ".txt");
    ByteArrayInputStream byteInputStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
//   ...other code
     method2(filename)
// ... more code
   } catch(...) {...}
 }

public void method2(filename){...do something here}
}

I want to test what's inside of the try statement however I'm unable to mock the InputStream so it just goes straight to the catch statement when I try to Spy on uploadFile. How can I mock the InputStream so it returns a file I have in the temp folder or just not go to the catch statement such that I may test the rest of my code. i.e.) I'm trying to verify method2 will be within the uploadFile method.

  • Mockito doesn't handle mocking `static` methods and `new` object creation, so either (a) refactor those out, or (b) Write a test datafile in `test/resources`, or (c) bring in PowerMockito as well - see https://github.com/powermock/powermock/wiki/mockito (esp "Mocking static methods" and "Mock construction of new objects") – racraman Feb 03 '20 at 02:36
  • @racraman I can't use powermockito with Junit5 + mockito 3+ +mockito-junit-jupiter 3.2.4 build – guest23921 Feb 03 '20 at 02:46
  • Shame - yes, seems PowerMock still doesn't support Junit5 . So that leaves my earlier options of (a) or (b) . – racraman Feb 03 '20 at 03:01
  • You may go through https://stackoverflow.com/questions/6371379/mocking-java-inputstream – Vivek Feb 03 '20 at 03:29

0 Answers0