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

What is the difference between the 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 understand that Assert.AssertNotNull is a function call from TestNG, and assert is the Java keyword (introduced in Java 1.4). Are there any other differences in the two? e.g. work, productivity, etc.

+7
source share
4 answers

Well, the first case uses the Assert class from your testing framework and is the right way, since TestNG will report the error in a smart 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 crash, but the stack trace may or may not be clear at a glance. You should also be aware that claims cannot be activated.

+7
source

Yes, there is: the assert keyword should be enabled using the -ea flag, for example

  java -ea MyClass 

An assertion can be turned on and off without any changes to the code.

The Assert class will always work. So, if you are testing, use the Assert class, not the assert keyword. This may give you an idea that all your tests pass, and in fact they do not claim anything. In the 10 years of my coding, I have never seen anyone include statements other than Jetbrains, so use Assert instead. Or better, use Hamcrest .

+3
source

Speaking of performance:

assert object!=null; is a single java statement, but Assert.assertNotNull(object) will cause several TestNG functions to be called, therefore wrt performance is assert object!=null; will be a little better.

+2
source

The difference is mainly in the absence of the assert keyword. This is the source from testng:

 static public void assertNotNull(Object object) { assertNotNull(object, null); } static public void assertNotNull(Object object, String message) { assertTrue(object != null, message); } 

Note that the OP used the testng tag!

This is not a JUnit assert !

Some information about the keyword java assert : assert

0
source

All Articles