I'm new using hamcrest. While I'm discovering how to use it I have been a doubt about when to use is
or equalTo
.
Is there any difference between is
and equalTo
, although it is conceptually or ocasionally? It seems to behave the same.
Assert.assertThat(actual, equalTo("blue"));
Assert.assertThat(actual, is("red"));
Why do you would use one instead of the other?
assertEquals() is the method of Assert class in JUnit, assertThat() belongs to Matchers class of Hamcrest. Both methods assert the same thing; however, hamcrest matcher is more human-readable. As you see, it is like an English sentence “Assert that actual is equal to the expected value”.
Hamcrest is a framework that assists writing software tests in the Java programming language. It supports creating customized assertion matchers ('Hamcrest' is an anagram of 'matchers'), allowing match rules to be defined declaratively. These matchers have uses in unit testing frameworks such as JUnit and jMock.
Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively. There are a number of situations where matchers are invaluable, such as UI validation or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used.
The Javadoc for Matchers
is pretty clear. is
in all its overloaded forms is there for expressiveness.
The "main" is
is is(Matcher<T> matcher)
which:
Decorates another Matcher, retaining its behaviour, but allowing tests to read slightly more like an English phrase.
For example:
assertThat(cheese, is(equalTo(smelly)))
instead of:
assertThat(cheese, equalTo(smelly))
is(T value)
is:
A shortcut to the frequently used
is(equalTo(x))
.
Allowing assertThat(cheese, is(smelly))
... and is(java.lang.Class<T> type)
is:
A shortcut to the frequently used
is(instanceOf(SomeClass.class))
.
Allowing assertThat(cheese, is(DairyFood.class))
... but this is deprecated in favour of isA(DairyFood.class)
.
What this boils down to is that is(foo)
and equalTo(foo)
are exactly equivalent in their behaviour, as long as foo
is neither a Matcher
nor a Class
. You should use whichever you feel communicates your intent most clearly.
According to the Docs, is(Object obj)
is just a shortcut for is(equalTo(Object obj))
, where you can use is
to compose more expressive matchers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With