【问题标题】:UnitTest C++ in VS (expected and actual values are the same but it's showing the mistake)VS 中的 UnitTest C++(预期值和实际值相同,但显示错误)
【发布时间】:2021-12-08 07:41:54
【问题描述】:

为什么显示测试失败,但预期值和实际值相同?有什么问题?

    #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);
    
            }
        };
    }

【问题讨论】:

  • this 很可能是您的问题,并且显示只是没有打印出这些变量的完整分辨率,因此它们看起来相等,但不是
  • 浮点相等是一个神话。
  • 这能回答你的问题吗? Is floating point math broken?

标签: c++ visual-studio unit-testing


【解决方案1】:

基本上问题是浮点类型存在舍入问题。详情请参阅this linked SO question。 计算结果不能用等号比较,但必须有一定的公差。

现在CppUnitTestFramework 考虑到这一点,并让您有机会提供这种容忍度。所以像这样修复你的测试:

#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);

        }
    };
}

参考:CppUnitTestFramework API documentation

验证两个双精度数是否相等

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

由于您只为 AreEqual 使用了 2 个参数,因此您的代码使用了此模板:

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

只使用相等运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-09
    • 2013-09-07
    • 1970-01-01
    • 2022-01-23
    • 2021-06-16
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    相关资源
    最近更新 更多