Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamcrest When to use Is or equalTo

Tags:

java

hamcrest

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?

like image 559
Pau Avatar asked May 25 '17 14:05

Pau


People also ask

Is assertThat actual is Equalto expected a valid Hamcrest assert statement?

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”.

What is the use of Hamcrest?

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.

What is Hamcrest in API?

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.


2 Answers

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.

like image 120
slim Avatar answered Oct 09 '22 20:10

slim


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.

like image 33
QBrute Avatar answered Oct 09 '22 20:10

QBrute