Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between assert object!=null and Assert.assertNotNull(object)?

What is the difference between following two blocks of code?

@Test  
public void getObjectTest() throws Exception {
    Object object;
    //Some code
    Assert.assertNotNull(object);
}

AND

@Test  
public void getObjectTest() throws Exception {
    Object object;
    //Some code
    assert object!=null;
}

I do understand that Assert.AssertNotNull is a function call from TestNG and assert is a key word of Java ( introduced in Java 1.4 ). Are there any other differences in these two ? e.g. working, performance etc

like image 514
Waleed Avatar asked May 22 '13 11:05

Waleed


3 Answers

Well the first case uses the Assert class from your testing framework and is the right way to go, since TestNG will report the error in an intelligent way.

You can also add your own message to the test:

Assert.assertNotNull(object, "This object should not be null");

The second case uses the assert keyword - it will give you a failure but the stack trace may or may not be understandable at a glance. You also need to be aware that assertions may NOT be enabled.

like image 195
vikingsteve Avatar answered Nov 10 '22 12:11

vikingsteve


Talking about Performance:

assert object!=null; is a single java statement but Assert.assertNotNull(object) will result in calling of Multiple functions of TestNG, so w.r.t. performance assert object!=null; will be slightly better.

like image 37
Raheel Avatar answered Nov 10 '22 13:11

Raheel


Yes, there is: the assert keyword needs to be enabled using the -ea flag, like

 java -ea MyClass

The assert can therefor be turned on and off without any changes to the code.

The Assert class will always work instead. So, if you're doing testing, use the Assert class, never the assert keyword. This might give you the idea all your tests are passing, and while actually they don't assert anything. In my 10+ years of coding, I've never seen anyone enable assertions except Jetbrains, so use Assert instead. Or better, use Hamcrest.

like image 3
Erik Pragt Avatar answered Nov 10 '22 12:11

Erik Pragt