c# - 自定义消息和默认消息

标签 c# unit-testing vs-unit-testing-framework

有没有办法为 Assert.AreEqual(object, object, string) 指定消息?将自定义消息与默认消息结合在一起?

我有以下代码:

foreach (var testCase in testCases)
{
    Assert.AreEqual(testCase.Value, myObj.myMethod(testCase.Key), combinedMessage);
}

除了来自下面 VS 单元测试框架的示例消息之外,我还想指定测试用例键:

Assert.AreEqual failed. Expected:<True>. Actual:<False>.

可能类似于 Failed on the following test case: AB .

最佳答案

重载会自动为你做这件事。作为测试,我做了这个测试方法来查看输出是什么:

    [TestMethod]
    public void Test()
    {
        Assert.AreEqual(true, false, "Failed on the following test case: AB");
    }

错误消息输出为:Assert.AreEqual failed. Expected:<True>. Actual:<False>. Failed on the following test case: AB

消息参数已经附加/组合到默认消息。

对于您的情况,如果您只想获取测试 key ,则测试可能如下所示:

foreach (var testCase in testCases)
{
    Assert.AreEqual(testCase.Value, myObj.myMethod(testCase.Key), 
        "Failed on the following test case: " + testCase.Key.ToString());
}

如果每个测试用例都应该有自己的自定义消息,那么将自定义错误消息移至 testCase 类就很有意义了。作为创建每个对象的一部分,您可以指定这三个属性:

testCase.Value = true;
testCase.Key = "AB";
testCase.FailureMessage = "Failed on the following test case: AB";

这种类型的结构允许为每个 testCase 实例附加一条指定的消息。这样做将使单元测试看起来像这样:

foreach (var testCase in testCases)
{
    Assert.AreEqual(testCase.Value, myObj.myMethod(testCase.Key), 
        testCase.FailureMessage));
}

并且您示例中的输出显示为:Assert.AreEqual failed. Expected:<True>. Actual:<False>. Failed on the following test case: AB

关于c# - 自定义消息和默认消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15229800/

相关文章:

c# - 为移动设备 (.NET) 在页面中排序框架( block )

c# - 在 C# 中使用 DateTime 和 TimeSpan 进行计算

android - 使用 Robolectric 在 Android Studio 中测试应用程序

regex - Dejagnu/期望多行正则表达式

c# - 扩展大值

c# - mefcontrib拦截目录导出错误

c# - NUnit测试调试

code-coverage - MSTest 代码覆盖率

visual-studio - 我应该初始化每个测试方法,还是只初始化类,或者两者都不初始化?

visual-studio-2013 - 如何更改测试资源管理器窗口以在下方而不是旁边显示测试源信息?