0

Why is it showing that the test failed, but the expected and actual values are the same? What is the problem?

image (Assert failed)

    #include "pch.h"
    #include "CppUnitTest.h"
    #include "../Lab 5_3/Lab 5_3.cpp"
    
    using namespace Microsoft::VisualStudio::CppUnitTestFramework;
    
    namespace UnitTest53
    {
        TEST_CLASS(UnitTest53)
        {
        public:
            
            TEST_METHOD(TestMethod1)
            {
                double t, g;
                g = 1;
                t = p(p(1 - 2 * g) + pow(p(1 - p(1) + (p(2 * g) * p(2 * g))), 2));
                Assert::AreEqual(t, 0.320469);
    
            }
        };
    }
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Olena
  • 1
  • 1
  • 1
    More than likely [this](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) is your issue, and the display is just not printing out the full resolution of those variables so they look equal, but aren't – NathanOliver Oct 21 '21 at 14:24
  • Something something floating point equality is a myth. – sweenish Oct 21 '21 at 14:28
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Ken White Oct 21 '21 at 14:44

1 Answers1

0

Basically problems is that there is a rounding issue for floating point types. For details see this linked SO question. Results of calculation should not be compared by equal operator, but some tolerance must be applied.

Now CppUnitTestFramework takes this into account and gives you a chance to provide this tolerance. So fix your test like this:

#include "pch.h"
#include "CppUnitTest.h"
#include "../Lab 5_3/Lab 5_3.cpp"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace UnitTest53
{
    TEST_CLASS(UnitTest53)
    {
    public:
        
        TEST_METHOD(TestMethod1)
        {
            double t, g;
            g = 1;
            t = p(p(1 - 2 * g) + pow(p(1 - p(1) + (p(2 * g) * p(2 * g))), 2));
            Assert::AreEqual(t, 0.320469, 0.000001);

        }
    };
}

Reference: CppUnitTestFramework API documentation

Verify that two doubles are equal

static void Assert::AreEqual(
       double expected,
       double actual,
       double tolerance,
       const wchar_t* message = NULL,
       const __LineInfo* pLineInfo = NULL)

Since you used only 2 arguments for AreEqual your code used this template:

template<typename T>
static void Assert::AreEqual(
    const T& expected,
    const T& actual,
    const wchar_t* message = NULL,
    const __LineInfo* pLineInfo = NULL)

which just uses equal operator.

Marek R
  • 32,568
  • 6
  • 55
  • 140