I have a method that during a specific point of processing it expects that certain invariants are kept.
To keep this trivial let’s say that at point X during the code processing the variable high and the variable low MUST be divisible.
So in the code I do:
if(high % low != 0){
throw new AssertionError("Invalid state of low and high [low = "+ low+ ", high=" + high+"]");
}
During unit testing with JUnits I had a test case to test for this.
So I did:
try {
//At this point I know for sure that the low and high are not divible so process() should throw an Assertion Error
process();
fail();
}
catch(AssertionError e){
}
But the test case was green!
But I realised that junit raises an assert error due to fail but I catch it and as a result the test case is pass instead of failed.
From my point of view the proper error to raise in my code is also AssertionError and not some generic e.g. IllegalArgumentsException
So is there a way to fix this so that the test case works or should I not be using the AssertionError in my code in the first place? If this is the case, what exception should I be raising?
But if the condition is an invariant, then it should always be true, and the AssertionError should thus never be thrown, and you should thus not even be able to unit test it. If you’re able to test it, it means that the invariant is not really an invariant, and that the condition might be true depending on the sequence of calls or on the arguments provided. You should thus prefer an IllegalStateExcetion over the AssertionError.