Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamcrest number comparison using between

Tags:

java

hamcrest

Is there a way in Hamcrest to compare a number within a number range? I am looking for something like this:

assertThat(50L, is(between(12L, 1658L))); 
like image 332
saw303 Avatar asked Oct 08 '12 14:10

saw303


People also ask

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.

Which Hamcrest matcher is just like the && operator?

Which Hamcrest matcher is just like the && operator? Explanation: Checks to see if all contained matchers match (just like the && operator). 7.

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.

What is the Hamcrest matcher to test if a string contains another string?

Class StringContains. Tests if the argument is a string that contains a substring. Creates a matcher that matches if the examined String contains the specified String anywhere.


2 Answers

An alternative to Jeff's solution is to use both:

assertThat(50L, is(both(greaterThan(12L)).and(lessThan(1658L)))); 

I think that's quite readable. You also get a good error message in case the check failed:

Expected: is (a value greater than <50L> and a value less than <1658L>) got: <50L>

like image 126
Christoph Leiter Avatar answered Sep 20 '22 04:09

Christoph Leiter


I don't believe between is part of the core hamcrest matchers, but you could do something like this:

assertThat(number, allOf(greaterThan(min),lessThan(max))); 

That's still a little ugly, so you could create a helper method between

assertThat(number, between(min,max)) 

and between looks like

allOf(greaterThan(min),lessThan(max)) 

Still not a fantastic solution, but it reads like a hamcrest matcher.

If you can't find one that's publicly available, it would be trivial to write your own between matcher http://code.google.com/p/hamcrest/wiki/Tutorial.

like image 44
Jeff Storey Avatar answered Sep 23 '22 04:09

Jeff Storey