Reputation: 66
I'm struggling with some strange behavior of an assertion within a JUnit test which confuses me a lot.
@Test
public void ArticleTest()
{
Article ArticeToTest = null;
assert(ArticeToTest.get_price() == price); //No exception here!?
boolean test = ArticeToTest.get_price() == price; //NullPointerException!
}
I don't really understand why the assertion is not causing any exception. It's even possible for me to run through this line in debug mode without any error, the exception occures only in the last line. If I delete the last line, the test appears to be green!?
I'm working with Eclipse Luna (4.4.0), javac 1.8.0_20 and JUnit 4.11.
Upvotes: 1
Views: 109
Reputation: 3749
The assert keyword is not supposed to throw an Exception
, it throws an Error
, if it is enabled in the JVM. It is used to test assumptions in code (ie. as a quick [read: lazy] way to do defensive programming) like whether a parameter is different form null, falls within accepted values, is a valid URL, etc. and should not be used for automated (unit) testing. For that you should use the testing frameworks Assert
class.
Upvotes: 1
Reputation: 2826
Try assertTrue() rather than assert(). Also, that just confuses people if your local variables are named starting with a capital letter.
EDIT: Ok, so what's going on with your test? I usually would expect any of these three things happening in a test: (1) Arrange (2) Act (3) Assert, such that almost certainly Assert is present as the last thing happening (unless there's an implied verify against mock objects, maybe). It's looking like you did mean to use the kind of assertion that is enabled with -ea when you run the code, but that's not what I expect to see in a test case.
Upvotes: 1
Reputation: 109255
The keyword assert
is not intended for verification during testing, but for establishing invariants that are checked at runtime if you tell java explicitly to check for them (using -ea
or -enableassertions
), see also Programming With Assertions. Note that this can be useful during testing, but it isn't the same as unit testing. If assertions are disabled (the default), then the entire statement is ignored.
However when unit testing, you need to use the assertion facility of your testing framework. For JUnit, this is org.junit.Assert
. It usually provides more functionality for communicating test failures, and it doesn't requiring enabling assertions as you need to do with assert
.
Upvotes: 3
Reputation: 11672
Java assertions are only active if the JVM is run with -ea (Enable Assertions).
Are you sure you're running it with -ea?
You can check this in your Eclipse run configurations.
Upvotes: 3