Is there anything like assertThat(a, lessThan(b));
? I'm currently using Junit 4.8.1 and I haven't been able to find lessThan. Instead I have to do assertTrue(a < b)
, but this has a drawback that it doesn't print two numbers in test log.
Asked
Active
Viewed 1.3k times
11

Shuo
- 4,749
- 9
- 45
- 63
-
It doesn't look like it. But you could easily write your own that provides a useful message... – Oliver Charlesworth Mar 10 '13 at 23:48
2 Answers
11
Have you tried JUnit + Hamcrest? See this blog post for some examples—it looks almost exactly like what you posted:
JUnit 4 Showcase – assertThat and Hamcrest Matchers
Alternatively, there's also ComparableAssert from the JUnit-addons project.

DaoWen
- 32,589
- 6
- 74
- 101
-
2
-
1It's in the docs: http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/number/OrderingComparison.html#lessThan(T) – DaoWen Mar 11 '13 at 03:50
-
1Or, if you go through `Matchers` to see everything that's available, as [`Matchers.lessThan`](http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#lessThan%28T%29). – Joe Mar 11 '13 at 11:26
-
2the `Matchers` class doesn't seem to come with the *Hamcrest* that *Junit* uses. Adding **Hamcrest-library**, as an additional dependency, got the me the necessary `Matchers` class. – Raystorm Feb 26 '14 at 01:02
3
You can import Hamcrest like this and use the Matchers.lessThan() method.
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
assertThat(foo, Matchers.lessThan(bar));

user2601995
- 6,463
- 8
- 37
- 41