Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assert(false) does not stop execution

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?

like image 687
Adam Matan Avatar asked Dec 12 '12 12:12

Adam Matan


People also ask

Does assert stop execution?

A triggered assertion indicates that the object is definitely bad and execution will stop.

What happens when assert is false?

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).

What happens when Python assert fails?

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.

What happens when assert fails in Java?

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.


2 Answers

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.

like image 115
Sean Owen Avatar answered Oct 08 '22 08:10

Sean Owen


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.

like image 35
Shervin Asgari Avatar answered Oct 08 '22 09:10

Shervin Asgari