断言很基本

时间:2013-03-12 09:31:54

标签: c# .net nunit

我正在阅读两个文件中的内容,现在我想用我期望的字符串测试该内容。

string read1 = File.ReadAllText("@C:\somefile.txt");
string read2 = File.ReadAllText("@C:\somefilee.txt");

string expectedString = "blah";

Assert.AreEqual(read1 and read2 equals expected );

我知道这是基本的,但我有点被困在这里。

4 个答案:

答案 0 :(得分:4)

您需要使用2个断言,首先将预期字符串与第一个文件内容进行比较,然后将第二个文件内容与第一个文件内容进行比较(或再次使用预期字符串),例如:

Assert.AreEqual(expectedString, read1, "File content should be equal to expected string");
Assert.AreEqual(read1, read2, "Files content should be identical");

或者您可以使用条件

Assert.IsTrue(read1 == read2 == expectedString, "Files content should be equal to expected string");

但在这种情况下,如果测试失败,你将无法知道问题是什么。

答案 1 :(得分:2)

我更喜欢使用普通的C#编写这样的断言,你可以使用ExpressionToCodenuget package)。有了这个,你的断言看起来如下:

PAssert.That(
    () => read1 == expectedString && read2 == expectedString
    , "optional failure message");

如果失败,库将在其输出中包含该表达式,并包含您使用的各种变量(read1,read2和expectedString)的实际值。

例如,您可能会遇到如下错误:

optional failure message
read1 == expectedString && read2 == expectedString
  |    |        |        |   |    |        |
  |    |        |        |   |    |        "blah"
  |    |        |        |   |    false
  |    |        |        |   "Blah"
  |    |        |        false
  |    |        "blah"
  |    true
  "blah"

免责声明:我写过ExpressionToCode。

答案 2 :(得分:1)

Assert(read1 == read2 && read1 == expectedString, "Not all equal")

答案 3 :(得分:-1)

如果我说得对,你想要这个:

try{
if(Assert.AreEqual(read1,read2,false)){
//do things
}
catch(AssertFailedException ex){
//assert failed
}

查看here以获取MSDN。

相关问题