Is it a good idea to catch AssertionError in JUnit tests?

I have an object as a result of an API call, and I want to validate the values ​​of a member variable.

This value can be one of two expected values, depending on what the API call "sees" first and sets first. Therefore, if an assertion about one value fails, I want to assert for another value before declaring the test as a failure.

What is the best way to do this? Now I have:

try { assertEquals("message", someObject.getValue1(), expectedValue1); } catch(AssertionError ae) { assertEquals("message", someObject.getValue1(), expectedValue2); } 

I'm just not sure if this is an acceptable practice. Please comment.

+7
java junit4
source share
3 answers

Using exceptions as a kind of glorified goto statement is usually not good practice. Or at least you will come across people in your career who dimly see the use of exceptions to control the flow of programs.

What about:

 Assert.assertTrue((someObject.getValue1().equals(expectedValue1) || (someObject.getValue2().equals(expectedValue2)); 
+7
source share

Depends on the goal, automatic functional testing or unit testing. I sometimes do this for the first:

 try { assertTrue(boolean condition from earlier in test method to check); } catch(AssertionError uhOh) { Logger.err("condition X failed: detailed info msg"); // broken item #1 } try { assertTrue(another condition in same method to check); } catch(AssertionError yuck) { Logger.err("condition X failed: detailed info msg"); // another broken item fail(); // now blow up as we've checked everything } 

Of course, using logback Logger and JUnit Assert.fail (), which does not execute the test method. Thus, I know all the failures for this method, and not the explosions after the first. In my case, I am testing a web application with rich content (dialogs and pages that require a lot of input).

The fail-fast downside (without catches) detects one problem, fixes it, starts it again and finds a new one (“rinse and repeat”), but if used for unit testing, this is an asset due to unit tests (ideally you check only one aspect of an element per test).

+5
source share

I agree with Aquilon that this is not good practice.

However, can you use a mocking or some other mechanism to "make" the API "see" one element in front of another? Thus, your tests may reflect conditions that lead to one statement that is true in one test, and another statement that is true in another test.

+1
source share

All Articles