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)));
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? Explanation: Checks to see if all contained matchers match (just like the && operator). 7.
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.
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.
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>
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.
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