【问题标题】:Assert.AreEqual vs Assert.IsTrue/Assert.IsFalseAssert.AreEqual 与 Assert.IsTrue/Assert.IsFalse
【发布时间】:2011-11-03 16:08:22
【问题描述】:

在测试返回类型为 bool 的方法时。

你应该有:

expected = true;
Assert.AreEqual(expected, actual);

或

Assert.IsTrue(actual);

我知道它们都产生相同的结果,但哪种做法更好?

编辑:例如,如果我执行 AreEqual,它是否与在返回以下字符串的方法上执行 IsTrue 本质上不同:

string expected = “true”;
string actual = test.testMethod(data)
bool test;

if expected.equals(actual)
    test = true;
else 
    test = false;
Assert.IsTrue(test);

【问题讨论】:

  • 在什么情况下你有一个变量 expected你知道总是正确的?也就是说,如果您知道它总是正确的,那么为什么首先要有一个变量呢?只需使用文字true。
  • @EricLippert:他正在尝试适应 VS 自动生成的模式,看起来一模一样(右键单击返回布尔值的方法,然后单击创建单元测试)。

标签: c# .net unit-testing


【解决方案1】:

只有在测试直接返回应该始终为 true 的布尔值时,才应使用 Assert.IsTrue。

您不应该通过按摩数据来获得 IsTrue 的布尔值;相反,您应该在Assert 或CollectionAssert 中调用更相关的方法。

在您编辑的示例中,您应该致电Assert.AreEqual;它会给你一个更好的信息。

【讨论】:

    【解决方案2】:

    使用Assert.IsTrue 更清晰,更简洁。

    【讨论】:

    • 而且测试失败的时候消息更好。
    • @Toto:Assert.IsTrue failed 怎么样?
    • 我只是测试。我记得消息是不同的,但没有。对不起。
    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 2014-12-11
    • 2011-06-30
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    相关资源
    最近更新 更多