Marcin Poloczek
Marcin Poloczek

Reputation: 993

Microsoft C++ Native Test Fails Assert::AreSame even when values are the same

I'm running a test with microsoft native unit testing framework (that comes with vs2019) and it fails with this message: Assert failed. Expected:<1> Actual:<1>

Here is the test code:

TEST_METHOD(memory_copy)
{
    int ref[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int src[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int dest[10];

    test::memory_copy<int>(src, dest, 10);

    for (unsigned int i = 0; i < 10; i++)
    {
        Assert::AreSame(src[i], ref[i]);
        Assert::AreSame(dest[i], ref[i]);
    }
};

Note: memory_copy<>() copies memory from one pointer to another, just like std::memcpy()

Does anyone have an idea what may be the issue here?

Upvotes: 0

Views: 351

Answers (2)

ChrisMM
ChrisMM

Reputation: 10021

Assert::AreSame() checks whether the inputs refer to the same object; it does not compare the values.

The implementation of the function (from CppUnitTestAssert.h) is as follows:

template<typename T> static void AreSame(const T& expected, const T& actual, const wchar_t* message = NULL, const __LineInfo* pLineInfo = NULL)
{
    FailOnCondition(&expected == &actual, EQUALS_MESSAGE(expected, actual, message), pLineInfo);
}

What you can see here, is that it's comparing memory addresses, as opposed to the contents. Assert::AreEqual, on the other hand, compares the objects for equality.

template<typename T> static void AreEqual(const T& expected, const T& actual, const wchar_t* message = NULL, const __LineInfo* pLineInfo = NULL)
{
    FailOnCondition(expected == actual, EQUALS_MESSAGE(expected, actual, message), pLineInfo);
}

Upvotes: 2

Marcin Poloczek
Marcin Poloczek

Reputation: 993

It turns out that Assert::AreSame() doesn't do what I expected it to do. By changing it to Assert::AreEqual() I've solved the issue. More info here:

Microsoft Documentation on AreEqual()

Upvotes: 0

Related Questions