11

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.

Shuo
  • 4,749
  • 9
  • 45
  • 63

2 Answers2

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
    I checked Hamcrest, and there was nothing like the lessThan function – Shuo Mar 11 '13 at 01:37
  • 1
    It'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
  • 1
    Or, 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
  • 2
    the `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