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