13

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

Waleed
  • 514
  • 1
  • 6
  • 17

4 Answers4

11

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.

vikingsteve
  • 38,481
  • 23
  • 112
  • 156
3

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.

Erik Pragt
  • 13,513
  • 11
  • 58
  • 64
  • This is being run inside a TestNG platform. TestNG enables assert statements. I'm not sure where you are getting your information. – Bob Dalgleish May 22 '13 at 12:11
3

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.

Waleed
  • 514
  • 1
  • 6
  • 17
Raheel
  • 4,953
  • 4
  • 34
  • 40
0

The difference is basically the lack of 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);
}

Please note that the OP used the testng tag!

This is not JUnit's Assert!

Some info about java's assert keyword: assert

Community
  • 1
  • 1
Adam Arold
  • 29,285
  • 22
  • 112
  • 207