Why file.bufferedReader()
is giving me NullPointerException
here?
val file = mock<File>()
when(file.bufferedReader()).thenThrow(IOException::class.java)
Why file.bufferedReader()
is giving me NullPointerException
here?
val file = mock<File>()
when(file.bufferedReader()).thenThrow(IOException::class.java)
According to this thread Unable to mock BufferedWriter class in junit
You can mock Java IO classes (including their constructors, so future instances also get mocked) with the JMockit library, though you will likely face difficulties such as a NullPointerException from the Writer() constructor (depending on how the mocking was done, and which IO classes were mocked).
However, note that the Java IO API contains many interacting classes and deep inheritance hierarchies. In your example, the FileWriter class would also probably need to be mocked, otherwise an actual file would get created.
Also, usage of IO classes in application code is usually just an implementation detail, which can easily be changed. You could switch from IO streams to writers, from regular IO to NIO, or use the new Java 8 utilities, for example. Or use a 3rd-party IO library.
Bottom line, it's just a terribly bad idea to try and mock IO classes. It's even worse if (as suggested in another answer) you change the client code to have Writers, etc. injected into the SUT. Dependency injection is just not for this kind of thing.
Instead, use real files in the local file system, preferably from a test directory which can be deleted after the test, and/or use fixed resource files when only reading. Local files are fast and reliable, and lead to more useful tests. Certain developers will say that "a test is not a unit test if it touches the file system", but that's just dogmatic advice.