Reputation: 677
My method is as follows:
public void variable_equal_to_ratio_of_and(String exp, String numerator, String denominator) {
double numerTotal = 0, denomTotal = 0;
String[] numerArray = numerator.split(",");
String[] denomArray = denominator.split(",");
System.out.println("PCT value " + exp);
for (String iterator: numerArray) {
numerTotal += Double.valueOf(iterator);
}
for (String iterator: denomArray) {
denomTotal += Double.valueOf(iterator);
}
double ratio = (numerTotal * 100) / (numerTotal + denomTotal);
ratio = ratio / 100;
BigDecimal bd = new BigDecimal(ratio).setScale(3, RoundingMode.HALF_DOWN);
double d = bd.doubleValue();
org.junit.Assert.assertEquals(Float.valueOf(exp), d, 0);
}
To figure out what the actual value should be for this ratio our customers view, I need to do some math to get the answer and store that answer in a double or float which is what you're seeing in this method. The problem is I then have to do an assert equals on what our test framework pulls from the API and there is no valid method to compare a float/double with a string for junit.Assert. I seem to be able to convert the String passed in to a float/double, but then both the expected value and actual value has to be the same number of decimal places or the assertion fails.
When I convert the expected value to two decimals, it seems to always be done by DecimalFormat or BigDecimal and neither of those I can pass into the assertion.
I can convert the expected value string to 2 decimals, but then when I pass it into the AssertEquals as a double/float, it parses it to as many decimals as it wants.
The developers coded the ratio in GoLang as Math.round(((123.54999) * 10) / 10); and tell me it's using this formula: "float32((float64(float32(number1) * 100 / float32(number2))) / 100)"
But, my QA lead has written our entire testing framework in Java.
How can I keep the expected value passed to the assertion as the same number of decimals that I've set the actual value to in BigDecimal?
Upvotes: 0
Views: 1723
Reputation: 834
To assert that 2 floating-point values are equal to some number of decimal places, you can change the epsilon
parameter on assertEquals
(the 3rd value)
For example,
Assert.assertEquals(Float.valueOf(exp), d, .01);
would assert that Float.valueOf(exp)
and d
are equivalent with an epsilon of .01
.
Upvotes: 2