I'm writing a unit test using JUnit and Hamcrest. I have been comparing double values using:
assertThat(result, is(0.5));
However, I'm now needing to compare calculated values and I don't want to have to compare against the full double value. Instead, I want to compare for closeness.
I've discovered a class called IsCloseTo
but I'm not sure how to use it in an assertThat
and I can't find any examples online.
What's the correct syntax to do something like the following?
// I can't do this as I need to know what methods/classes whatever I should be using
// isCloseTo doesn't exist.
assertThat(result, isCloseTo(0.5, 0.1));
Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.
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.
This is great except that TestNG has soft assertions which can't be used from Hamcrest.
You should be able to call Matchers.closeTo(double, double)
. With a static import, it looks like:
assertThat(result, closeTo(0.5, 0.1));
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