Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare doubles using JUnit and Hamcrest?

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)); 
like image 887
Tim B Avatar asked Dec 18 '15 16:12

Tim B


People also ask

Does JUnit include Hamcrest?

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.

What is Hamcrest used for?

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.

Can we use Hamcrest with TestNG?

This is great except that TestNG has soft assertions which can't be used from Hamcrest.


1 Answers

You should be able to call Matchers.closeTo(double, double). With a static import, it looks like:

assertThat(result, closeTo(0.5, 0.1));
like image 184
nickb Avatar answered Oct 21 '22 23:10

nickb