你如何在Assert.Equal C#中使用通配符

时间:2017-04-28 00:49:50

标签: c#

我正在尝试比较一个字符串但是我的字符串中的文档no总是不同的,我不希望我的单元测试失败。我真的只是想检查文件是否发布。

在我的例子中,文件号可能不匹配。

Assert.AreEqual("1 Document(s) Posted. Document QA00752 has been created.", 
    message, "Post Confirmation Message does not match expected");

有什么建议吗?通过检查数据库中的数据并将其写入变量,我可以找出文档不应该是什么,但我不知道如何将它放在上面的语句中。

string doc = "some code goes here"

也许

Assert.AreEqual("1 Document(s) Posted. Document " + doc + " has been created.", 
    message, "Post Confirmation Message does not match expected");

3 个答案:

答案 0 :(得分:1)

如果您需要模式匹配,那么正则表达式(如SLaks所述)是最简洁的方法:

Assert.IsTrue(
    Regex.IsMatch(message, @"1 Document\(s\) Posted. Document QA\d+ has been created."),
    "Post Confirmation Message does not match expected");

答案 1 :(得分:1)

我认为尝试解析消息以删除特定标识符是有问题的。如果这只是一次性的事情,并且您不会在测试中检查各种字符串作为习惯,那么一个简单的.Contains或正则表达式就可以工作。

但是,如果你在整个地方都在做这个任务,那么也许一些抽象是有序的。您是否考虑过将日志消息变成对象而不是简单的字符串?

public sealed class Notification {
   public string Message { get; set; }
   public string Identifier { get; set; }
   public int? Count { get; set; }
}

然后,当您使用这些通知(例如在单元测试中)时,您可以比较Message属性以查看它是否相同,但忽略Identifier和{ {1}}。

以下是另一种方法:

Count

您可以像这样创建:

public sealed class InterpolatedString {
   public InterpolatedString(string stringWithPlaceholders, params string[] values) {
      StringWithPlaceholders = stringWithPlaceholders;
      Values = values;
   }

   public string StringWithPlaceholders { get; }
   public string[] Values { get; }
   public override string ToString() => string.Format(StringWithPlaceholders, Values);
}

然后,在测试或分组时,您可以访问非插值字符串。

return new InterpolatedString(
   "{0} Document(s) Posted. Document {1} has been created.",
   $"{count:#,##0}",
   documentCode
);

最后,只要你想要实际的字符串,就可以执行var actual = DoTest(); Assert.AreEqual( "{0} Document(s) Posted. Document {1} has been created.", actual.StringWithPlaceholders ); 或者在编译器支持的字符串隐式转换发生时隐式运行它。

如果更改代码中的字符串,则必须重复字符串以及破坏单元测试的风险。但是,如果您将字符串放入资源文件中,那么您甚至不需要在两个地方重复它们 - 您只需使用资源文件将它们吐出即可。另一种选择是将字符串保存在公共静态成员中,而不是嵌入代码深处。

答案 2 :(得分:0)

断言邮件包含("已创建"),除非有条件不通过。