Skip to content
Advertisement

How do you assert that a certain exception is thrown in JUnit tests?

How can I use JUnit idiomatically to test that some code throws an exception?

While I can certainly do something like this:

JavaScript

I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.

Advertisement

Answer

It depends on the JUnit version and what assert libraries you use.

The original answer for JUnit <= 4.12 was:

JavaScript

Though answer has more options for JUnit <= 4.12.

Reference:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement