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

It depends on the JUnit version and what assert libraries you use. For JUnit5 and 4.13 see answer https://stackoverflow.com/a/2935935/2986984 If you use assertJ or google-truth, see answer https://stackoverflow.com/a/41019785/2986984 The original answer for JUnit <= 4.12 was: @Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); } Though answer … Read more

Best practice for using assert?

Asserts should be used to test conditions that should never happen. The purpose is to crash early in the case of a corrupt program state. Exceptions should be used for errors that can conceivably happen, and you should almost always create your own Exception classes. For example, if you’re writing a function to read from … Read more

Static assert in C

C11 standard adds the _Static_assert keyword. This is implemented since gcc-4.6: _Static_assert (0, “assert1”); /* { dg-error “static assertion failed: \”assert1\”” } */ The first slot needs to be an integral constant expression. The second slot is a constant string literal which can be long (_Static_assert(0, L”assertion of doom!”)). I should note that this is … Read more