View Javadoc
1   /*
2    * Copyright (c) 2006 JMockit developers
3    * This file is subject to the terms of the MIT license (see LICENSE.txt).
4    */
5   package mockit.internal.expectations.argumentMatching;
6   
7   import edu.umd.cs.findbugs.annotations.NonNull;
8   import edu.umd.cs.findbugs.annotations.Nullable;
9   
10  /**
11   * Matches a decimal argument against another within a given margin of error.
12   */
13  public final class NumericEqualityMatcher implements ArgumentMatcher<NumericEqualityMatcher> {
14      private final double value;
15      private final double delta;
16  
17      public NumericEqualityMatcher(double value, double delta) {
18          this.value = value;
19          this.delta = delta;
20      }
21  
22      @Override
23      @SuppressWarnings("FloatingPointEquality")
24      public boolean same(@NonNull NumericEqualityMatcher other) {
25          return value == other.value && delta == other.delta;
26      }
27  
28      @Override
29      @SuppressWarnings("ParameterNameDiffersFromOverriddenParameter")
30      public boolean matches(@Nullable Object decimalValue) {
31          return decimalValue instanceof Number && actualDelta((Number) decimalValue) <= delta;
32      }
33  
34      private double actualDelta(@NonNull Number decimalValue) {
35          return Math.abs(decimalValue.doubleValue() - value);
36      }
37  
38      @Override
39      public void writeMismatchPhrase(@NonNull ArgumentMismatch argumentMismatch) {
40          argumentMismatch.append("a numeric value within ").append(delta).append(" of ").append(value);
41      }
42  }