5

I want to use a Hamcrest matcher inside a TestNG test and with a soft assert specifically. How can I do this? I know that I can use Hamcrest's assertions inside a test like:

assertThat(actual, containsInAnyOrder(expected));

But I can't understand how can I use TestNG soft assert method like this one:

SoftAssert softAssert = new SoftAssert();

together with a Hamcrest matcher.

Because I can't invoke the Hamcrest's assertThat on TestNG's softAssert like softAssert.assertThat(...)

So, what is the correct way to use a Hamcrest matcher together with TestNG?

Vitali Plagov
  • 722
  • 1
  • 12
  • 31

1 Answers1

3

To the best of my knowledge, you cannot directly blend SoftAssert from TestNG with the hamcrest matcher assertions.

But you can make use of org.assertj.core.api.SoftAssertions within the hamcrest matcher library for trying to do soft assertions.

The javadocs for SoftAssertions has some samples.

For the sake of completeness, I am including the code snippet from the javadocs here.

 @Test
 public void host_dinner_party_where_nobody_dies() {
   Mansion mansion = new Mansion();
   mansion.hostPotentiallyMurderousDinnerParty();
   SoftAssertions softly = new SoftAssertions();
   softly.assertThat(mansion.guests()).as("Living Guests").isEqualTo(7);
   softly.assertThat(mansion.kitchen()).as("Kitchen").isEqualTo("clean");
   softly.assertThat(mansion.library()).as("Library").isEqualTo("clean");
   softly.assertThat(mansion.revolverAmmo()).as("Revolver Ammo").isEqualTo(6);
   softly.assertThat(mansion.candlestick()).as("Candlestick").isEqualTo("pristine");
   softly.assertThat(mansion.colonel()).as("Colonel").isEqualTo("well kempt");
   softly.assertThat(mansion.professor()).as("Professor").isEqualTo("well kempt");
   softly.assertAll();
 }

If you take a look at the SoftAssertions codebase, you would notice that the comments say that its been inspired by Cedric's blog on soft assertions.

Krishnan Mahadevan
  • 14,121
  • 6
  • 34
  • 66
  • Yes, I saw blog posts about AssertJ and SoftAssertions. But I can use only TestNG and Hamcrest in my project. So, I should try to use matchers built-in TestNG if I want to use SoftAssert. – Vitali Plagov Sep 03 '18 at 21:26
  • Yes, `SoftAssertions` is part of the same hamcrest jar. The TestNG `SoftAssert` API doesn't give you the feel of what a hamcrest matcher gives. But both do the same thing. So if you are used to the hamcrest like APIs for your assertion, then use `SoftAssertions` to continue to get the same feel. Else you can use `SoftAssert` from TestNG. – Krishnan Mahadevan Sep 04 '18 at 02:50
  • 1
    You're probably confusing because `SoftAssertions` is not part of the Hamcrest. It is part of [AssertJ](http://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/SoftAssertions.html). – Vitali Plagov Sep 04 '18 at 06:56