使用字符串断言 BSTR

Assert a BSTR with string

我有一个测试函数如下:

    [TestMethod]
    void RipMichaelJacksonTest()
    {
        string expected = "Hello";
        BSTR actual = SysAllocString(L"Hello");
        Assert::AreEqual(expected, actual);
    }

assert部分当然会失败。

有没有我可以使用的断言函数? 我是 VC++ 的新手。

问题是你正在做一个 AreEqual. Passing in two parameters will force AreEqual(Object^, Object^) 其中:

Verifies that two specified objects are equal. The assertion fails if the objects are not equal.

您实际上要查找的是 wchar*char* 的比较。两者之间没有直接比较功能,因此需要将 string 转换为 wstring。有很多关于如何做到这一点的例子,例如: 你需要做类似的事情,例如:

wstring get_wstring(const string& s) {
    wstring buf;
    const char* cs = s.c_str();
    const size_t wn = mbsrtowcs(nullptr, &cs, 0, nullptr);

    if (wn == string::npos) {
        cout << "Error in mbsrtowcs(): " << errno << endl;
    } else {
        buf.resize(wn + 1);

        if(mbsrtowcs(&*buf.begin(), &cs, wn + 1, nullptr) == string::npos) {
            cout << "Error in mbsrtowcs(): " << errno << endl;
            buf.resize(0);
        }
    }

    return buf;
}

get_wstring(expected)actual 的 return 现在都是 wchar,因此可以在使用 AreEqual(String^, String^, bool)[=25= 时进行比较]