Hamcrest When to use Is or equalTo
Asked Answered
B

2

22

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?

Bashibazouk answered 25/5, 2017 at 14:34 Comment(1)
is internally uses the equalsTo. I think its mostly for better readability.Liquescent
S
31

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.

Suggestion answered 25/5, 2017 at 14:45 Comment(0)
W
2

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.

Whyte answered 25/5, 2017 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.