jGleitz/JUnit-KIT

Check catching of IO Exceptions

Opened this issue · 8 comments

I don't think it makes sense to test every runtime exception that can possibly occur. No program can catch everyting.
But the task sheet mentiones explicitly that one is obliged to catch an IOException. Therefore, we should test for it.

But how to simulate an IOException? We can't even rely on a certain class the tested class uses to read in the file (If we could, we could simply mock that class and throw an exception).

Most I/O operations work on Files. So e.g. throw an exception in java.io.File's constructor. (However this will probably only test a very small code path in many programs.)

However this will probably only test a very small code path in many programs.

Do you thereby mean it's unnecessary to test it?

Sorry, this was nonsense anyway. File isn't supposed to throw IOException in its constructor.
Best way would be intercepting calls to Reader#read and InputStream#read, no idea how to do that though.

Best way would be intercepting calls to Reader#read and InputStream#read, no idea how to do that though.

That's easy, the mocking framework is all there. We simply write a InputStream/Reader that always throws that exception and mock. But how sure can we be that someone uses these classes?

If we e.g. mock FileInputStream and FileReader, will the JDK's subclasses of them use these implementations too?

I'm not completely sure, but I think so. Until now, our class loader does not allow mocking of java classes, but that's only for security reasons, it should be possible just the same.
Once that happens, any class loaded by the tested class will ask our class loader for its parent class, which we might have mocked.

side note: FileReader just uses FileInputStream

Loading a class that is in the java package is prohibited by default. I don't know how to trick Java into allowing me to do so in the moment, if it's possible at all.