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?
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 be slightly more expressive.
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.