Are AssertionErrors restrictions forbidden if I want to use JUnit?

I have a method that expects some invariants to be preserved during a certain processing point.
To keep this trivial, let's say that at point X, during the processing of the code, the variable highand the variable lowMUST 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 help JUnits, I had a test case to test 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){        
}

!
, junit assert - fail, , - .
, AssertionError, - , . IllegalArgumentsException
, , , AssertionError ? , ?

+3
4
boolean shouldFail = false;
try {
    callTheMethod();
    shouldFail = true;
}
catch (AssertionError e) {
    // expected
}
if (shouldFail) {
    fail();
}

, , AssertionError , unit test. , , . IllegalStateExcetion AssertionError.

+1

try-catch unit test. , :

@Test(expected=Exception.class)
public void youTestMethod() {
   ...
}

, IllegalArgumentsException, JUnit AssertionError . IllegalArgumentsException , .

+2
 > should I not be using the AssertionError in my code in the first place? 

JUnit AssertionError , junit-runner, . (Simmilar .net NUnit-runner)

 > If this is the case, what exception should I be raising? 

Exceptoin IllegalArgumentsException

0

, JUnit, .

JUnit, , AssertionError, .

JUnit , , AssertionError /.

( ) -

. - AssertionError.

//test case setup
yourClass.callYourMethod(4,2);
//verification

, , AssertionError, JUnit , .

. - AssertionError, .

boolean failed;
try {
    //test case setup
    yourClass.callYourMethod(4,2);
    failed = true;
} catch (AssertionError e) {
    failed = false;
}
if (failed) {
    fail();
}
0

All Articles