All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.thucydides.core.matchers.BigDecimalValueMatcher Maven / Gradle / Ivy

package net.thucydides.core.matchers;

import com.google.common.base.Optional;
import net.thucydides.core.reflection.FieldValue;
import org.hamcrest.Matcher;
import org.hamcrest.core.Is;
import org.hamcrest.core.IsEqual;

import java.math.BigDecimal;

import static org.hamcrest.Matchers.closeTo;

public class BigDecimalValueMatcher {
    private final Number value;
    private final Matcher matcher;

    protected BigDecimalValueMatcher(Number value, Matcher matcher) {
        this.value = value;
        Object expectedValue = expectedValue(matcher);
        if ((matcher instanceof IsEqual) || (matcher instanceof Is)) {
            this.matcher = closeTo(new BigDecimal(expectedValue.toString()), new BigDecimal("0"));
        } else {
            this.matcher = matcher;
        }
    }

    private Object expectedValue(Matcher matcher) {
        if (matcher.getClass() == Is.class) {
            Matcher innerMatcher = (Matcher) FieldValue.inObject(matcher).fromFieldNamed("matcher").get();
            Optional fieldValue = FieldValue.inObject(innerMatcher).fromFieldNamed("expectedValue");
            if (!fieldValue.isPresent()) {
                fieldValue = FieldValue.inObject(innerMatcher).fromFieldNamed("expected");
            }
            return fieldValue.orNull();
        } else {
            Optional fieldValue = FieldValue.inObject(matcher).fromFieldNamed("expectedValue");
            if (!fieldValue.isPresent()) {
                fieldValue = FieldValue.inObject(matcher).fromFieldNamed("expected");
            }
            return fieldValue.orNull();
        }
    }

    public boolean matches() {
        return matcher.matches(new BigDecimal(value.toString()));
    }
}