Skip to content

closeTo is confused by floats when chained #444

@basilevs

Description

@basilevs

Following snippet fails with:

Expected: hasProperty("number", a numeric value within <0.1> of <0.99>)
     but:  property 'number' was a java.lang.Float (<1.0F>)
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS org.hamcrest:hamcrest:3.0

import static org.hamcrest.Matchers.*;
import org.hamcrest.Matchers;
import org.hamcrest.Matcher;
import org.hamcrest.FeatureMatcher;
import static org.hamcrest.MatcherAssert.assertThat;

public class hello {
    public float getNumber() {
        return 1.0f;
    }
    public static void main(String... args) throws Exception {
        var subject = new hello();
        assertThat(subject, hasProperty("number", asDouble(closeTo(0.99, 0.1)))); // pass
        assertThat(subject, hasProperty("number", asDouble(is(closeTo(0.99, 0.1))))); // pass
        assertThat(subject, hasProperty("number", closeTo(0.99, 0.1))); // fail
        assertThat(subject, hasProperty("number", is(closeTo(0.99, 0.1)))); // fail
        System.out.println("Success");
    }
    public static Matcher<Float> asDouble(Matcher<Double> matcher) {
        return new FeatureMatcher<Float, Double>(matcher, "a Float", "double value") {
            @Override
            protected Double featureValueOf(Float actual) {
                       return Double.valueOf(actual);
                }
        };
    }
}

It should not fail as float property is a close number and should match, just like it does when Matchers are not chained.

Stackoverflow question

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions