Thursday, December 7, 2017

Asserting floating point values in unit tests


Just a few methods to help out with unit testing, mainly for asserting floating point values (float, double) to be within a tolerance of the expected value

public static class Dessert
{
    public static void AreEqual(double expected, double actual, double tolerance)
    {
        Assert.IsTrue(expected.IsEqual(actual, tolerance),
            $"{Environment.NewLine}Dessert.AreEqual(double, double) failed. Expected:<{expected}>. Actual<{actual}>. Tolerance<{tolerance}>");
    }
        
    public static void AreEqual(float expected, float actual, float tolerance)
    {
        Assert.IsTrue(expected.IsEqual(actual, tolerance),
            $"{Environment.NewLine}Dessert.AreEqual(float, float) failed. Expected:<{expected}>. Actual<{actual}>. Tolerance<{tolerance}>");
    }
}

How to use:

Dessert.AreEqual(2700, weight, 0.000000000000001);

All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment, not required but appreciated! :)

Hope this helps someone out there!

No comments:

Post a Comment