In one of my JUnit test, I'm initializing an object:
MyObject myObject = new MyObject(220, 120, 0.05, true);
The constructor's signature is:
public MyObject(int minLength, int maxLength,
double onBitsRatio, boolean forceAtLeastOneBitOn)
Followed by:
assert(onBitsRatio >= 0.0 && onBitsRatio <= 1.0);
assert(maxLength>=minLength);
assert(false);
Oddly enough, the assertions don't stop the execution, as I expect them to.
Why is JUnit ignoring these assertions?
A triggered assertion indicates that the object is definitely bad and execution will stop.
If assertions are enabled, assert false will unconditionally throw an AssertionError which derives from Error . But since assertions can be disabled, there are two problems, the error might go undetected and. control flow analysis requires a dummy return statement after the assert (which is mostly clutter).
If an assertion fails, then your program should crash because a condition that was supposed to be true became false. You shouldn't change this intended behavior by catching the exception with a try … except block. A proper use of assertions is to inform developers about unrecoverable errors in a program.
An assertion allows testing the correctness of any assumptions that have been made in the program. An assertion is achieved using the assert statement in Java. While executing assertion, it is believed to be true. If it fails, JVM throws an error named AssertionError.
JUnit is not ignoring these assertions, because as you say, you are using Java's assert
keyword. This is handled by the JVM, not JUnit.
The answer is almost certainly that your JVM assertions are turned off. In fact they are off unless you turn them on with -ea
. These are ignored otherwise.
Are you sure you are using proper assert from JUnit?
If you are using normal java assert, these are turned off by default. You have to enable them explicitly.
Try to use this: org.junit.Assert.assertTrue(false)
As far as I know, there is no method in the JUnit Assert library that is called just assert()
Seeing as your asserts are in some object, and you want the test to fail, then you need to enable the assert. Take a look at this tutorial describing how you can enable assertions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With