1

I'm a little bit confused in testNG assertion methods. My question is simple - is there any difference between Assert.assertTrue and Assertion?

I mean difference between following:

Assert.assertTrue(true);

And:

Assertion hardAssert = new Assertion();
hardAssert.assertTrue(true);

And why we need multiple ways to do checks?

  • 2
    Assert is the original API. Assertion is a base class that allows for extensions like SoftAssertion. Assert is there for backward compatibility. See rameshbaskar.wordpress.com/2013/09/11/…. – user246 Jun 15 '15 at 16:20
  • So, I can just use Assertion and forget about Assert? – Pasha Jun 15 '15 at 19:33
  • 1
    Even though you don't mention it, you might be interested in taking a look at hamcrest. It's assert method is really great and flexible. Take a look at this if you're interested: code.google.com/p/hamcrest/wiki/Tutorial another great thing about hamcrest is how easy it is to make your own matcher objects to assert whatever rule you want. Edit: I mention it because it complements TestNG exceptionally well. – Julian Jun 17 '15 at 2:56
1

Assert is the original API. Assertion is a base class that allows for extensions like SoftAssertion. Assert is there for backward compatibility. See https://rameshbaskar.wordpress.com/2013/09/11/soft-assertions-using-testng/ for more on soft assertions.

1

Hamcrest wasn't included in the question, but since Hamcrest complements TestNG quite well, this may be useful.

Another way to assert is using Hamcrest's MatcherAssert.assertThat methods.

This can be used alongside Hamcrest's large assortment of matcher objects to define conditions, such as:

int someActualValue = 5;
MatcherAssert.assertThat("This message prints if the assert fails!", 
    someActualValue, Matchers.greaterThanOrEqualTo(4));

or if we wanted to statically import MatcherAssert and Matchers for convenience:

assertThat("This message prints if the assert fails!", 
    someActualValue, greaterThanOrEqualTo(4));

for more syntactic sugar:

assertThat("This message prints if the assert fails!", 
    someActualValue, is(greaterThanOrEqualTo(4)));

Hamcrest also makes it pretty easy to create your own Matchers implementations to create custom assertion rules that you can use across your project.

This is an introduction for using hamcrest https://code.google.com/archive/p/hamcrest/wikis/Tutorial.wiki

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.