Assert.AreEqual(…)给了我一个System.FormatException

本文关键字:一个 System FormatException AreEqual Assert | 更新日期: 2023-09-27 18:10:56

Assert.AreEqual(expected, actual, "The value returned for {0}'s Foo method should be 'Bar'.",
            typeof(Calculator));
Assert.AreEqual(expected, actual, "The value returned for {0}'s Foo method should be 'Bar'.",
            typeof(Calculator).Name);

这两行都抛出了:

测试方法MyTesting。FooTest抛出异常:系统。FormatException:输入字符串格式不正确。


System.Text.StringBuilder。AppendFormat (IFormatProvider提供者,字符串格式,对象[]args)
System.String.Format (IFormatProvider提供者,字符串格式,对象[]args)
MyTesting.FooTest ()C:'TFS'Scratchpad'MyLibrary'Unit Testing'FooTest.cs: line 195

奇怪的是,我只有在单元测试失败时才会得到一个异常,当它通过时,我没有得到这个异常。我不期望出现异常,相反,它应该由于断言而失败,而不是因为单元测试本身抛出了异常。

Assert.AreEqual(…)给了我一个System.FormatException

在进行相等性测试之前,进行测试以确保您的对象Calculator不为空。

这种错误将在字符串格式的特殊情况下发生

尝试不使用格式化字符串,看看它是否仍然失败。我今天刚刚遇到了同样的问题,试图对结构进行断言,这样做可以阻止我的断言抛出格式异常。它似乎有格式化字符串的问题。(我使用ms测试)

Assert.AreEqual(expected, actual,"The value returned for " + typeof (Calculator) + "'s Foo method should be 'Bar'.");
Assert.AreEqual(expected, actual, "The value returned for " + typeof(Calculator) + "'s Foo method should be 'Bar'.");

我不喜欢这样构建字符串,但这是我能让我的测试正常运行的唯一方法。

相关文章: