Home > Blockchain >  Is there a way to test that a Java method does not throw a specific type of exception?
Is there a way to test that a Java method does not throw a specific type of exception?

Time:12-02

I am just looking at assertDoesNotThrow() in the JUnit documentation here. I know that you can specify the type of exception with assertThrows() but it appears from the documentation that you cannot do that with assertDoesNotThrow(). Is there a particular reason for that? If you wanted to show that, for example, a method does not throw a ParseException, how would you go about doing that?

CodePudding user response:

The default for a Java test is that it asserts that the function doesn't throw. You don't need to do any extra work for that; you only need to do extra work to allow it to throw.

To test that a method does not throw a ParseException, run it. That's all.

CodePudding user response:

Trying to prove a method does not throw exception is like saying purple unicorns don't exist. One has to check every spot in the universe to prove that. On the other hand if you check the spots where purple unicorns might live and don't see any of them, you can approximate and tell they don't exist in this context.

So while testing methods to see if they behave as expected, you test edge cases, boundary conditions. And for some of those cases you expect your method to throw exceptions, hence the assertThrows().

Other than that it's not possible/meaningless to try to prove a method does not throw exceptions in Java. Because you can't prove a method is pure, i.e. it will behave exactly same every time you run it.

  • Related