Thursday, 5 April 2018

Hamcrest: closeTo: Working with numbers

Suppose if the salary of the employee is 12345.6, you would like to match all the employees with some error + (or) – 1.2. then you can use these matchers.

Hamcrest provides closeTo matcher to match double and bigDecimals with given error.

For example, below statements match bigdecimals with delta + (or) - 0.05
assertThat(new BigDecimal("1.05"), closeTo(new BigDecimal("1.0"), new BigDecimal("0.05")));
assertThat(new BigDecimal("1.05"), closeTo(new BigDecimal("1.10"), new BigDecimal("0.05")));

Below statements match decimals with delta + (or) – 0.06
assertThat(1.05, closeTo(1.0, 0.06));
assertThat(1.05, closeTo(1.10, 0.06));

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.closeTo;

import java.math.BigDecimal;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  assertThat(new BigDecimal("1.05"), closeTo(new BigDecimal("1.0"), new BigDecimal("0.05")));
  assertThat(new BigDecimal("1.05"), closeTo(new BigDecimal("1.10"), new BigDecimal("0.05")));

  assertThat(1.05, closeTo(1.0, 0.06));
  assertThat(1.05, closeTo(1.10, 0.06));
 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment