有没有办法为 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/