如何实现XUnit描述性断言消息?
上下文
在XUnit github中我发现了这个: 添加Assert.Equal(预期,实际,消息)重载#350 (所以开发人员要求不存在的重载请参见下文)
引用答案:
我们相信自我记录的代码; 包括你的断言。
(所以XUnit团队拒绝它)
好,我知道了。 我也相信自我记录代码。 我还是找不到这个用例:
样品
// Arrange // Create some external soap service client and its wrapper classes // Act // client.SomeMethod(); // Assert // Sorry, soap service's interface, behaviour and design is *given* // So I have to check if there is no Error, and // conveniently if there is, then I would like to see it in the assertion message Assert.Equal(0, client.ErrorMessage.Length); // Means no error // I would like to have the same result what would be the following *N*U*n*i*t* assert: // Assert.AreEqual(0, client.ErrorMessage.Length, client.ErrorMessage); // Means no error
题
在这种情况下,如何在XUnit中实现描述性断言消息仍然没有这样的重载?
使用链接提供的建议。 像流畅的断言或创建自己的断言,包含Assert.True or Assert.False
,这些断言留下了他们的消息重载。 它被进一步提到了
引用
您可以向Assert.True和.False提供消息。 如果你根本无法生活没有消息(并拒绝使用不同的断言),你总是可以回到:
Assert.True(number == 2, "This is my message");
引用:
如果你真的想要有消息,可以在测试项目中添加Fluent Assertions或xbehave并使用它们的语法。 Fluent Assertions甚至会在遇到其存在时抛出xunit.netexception。
我遇到了同样的问题。 我有一个测试,从两个web api中提取数据,然后比较和断言有关内容的各种事情。 我开始使用标准的XUnit断言,例如:
Assert.Equal(HttpStatusCode.OK, response1.StatusCode); Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
但是虽然这给出了返回404的有用消息,但是从我们的构建/ CI服务器上的日志中不清楚哪个服务导致了错误消息。
我最后添加了自己的断言来给出上下文:
public class MyEqualException : Xunit.Sdk.EqualException { public MyEqualException(object expected, object actual, string userMessage) : base(expected, actual) { UserMessage = userMessage; } public override string Message => UserMessage + "\n" + base.Message; } public static class AssertX { /// /// Verifies that two objects are equal, using a default comparer. /// /// The type of the objects to be compared /// The expected value /// The value to be compared against /// Message to show in the error /// Thrown when the objects are not equal public static void Equal(T expected, T actual, string userMessage) { if (!expected.Equals(actual)) { throw new MyEqualException(expected, actual, userMessage); } } }
然后我可以做同样的断言:
Assert.Equal(HttpStatusCode.OK, response1.StatusCode, $"Fetching {Uri1}"); Assert.Equal(HttpStatusCode.OK, response2.StatusCode, $"Fetching {Uri2}");
并且错误日志给出了关于哪个webapi是罪魁祸首的实际,预期和前置。
我意识到我迟到了,但想到这可能有助于其他人寻找一个实用的解决方案,没有时间安装/学习另一个测试框架,只是为了从测试失败中获取有用的信息。