上下文
在XUnit github中我发现了这个:Add Assert.Equal(expected, actual, message) overload #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中实现描述性断言消息仍然没有这样的重载?
使用链接提供的建议。像fluent assertions或创建自己的断言包裹Assert.True or Assert.False
留下他们的消息超载。它被进一步提到了
您可以向Assert.True和.False提供消息。如果你根本不能没有消息(并且拒绝使用不同的断言),你总是可以回到:
Assert.True(number == 2, "This is my message");
如果你真的想要留言,你可以将Fluent Assertions或xbehave添加到你的测试项目并使用它们的语法。 Fluent Assertions甚至会在遇到其存在时抛出xunit.net异常。
我遇到了同样的问题。我有一个测试,从两个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
{
/// <summary>
/// Verifies that two objects are equal, using a default comparer.
/// </summary>
/// <typeparam name="T">The type of the objects to be compared</typeparam>
/// <param name="expected">The expected value</param>
/// <param name="actual">The value to be compared against</param>
/// <param name="userMessage">Message to show in the error</param>
/// <exception cref="MyEqualException">Thrown when the objects are not equal</exception>
public static void Equal<T>(T expected, T actual, string userMessage)
{
bool areEqual;
if (expected == null || actual == null)
{
// If either null, equal only if both null
areEqual = (expected == null && actual == null);
}
else
{
// expected is not null - so safe to call .Equals()
areEqual = expected.Equals(actual);
}
if (!areEqual)
{
throw new MyEqualException(expected, actual, userMessage);
}
}
}
然后我可以做同样的断言:
AssertX.Equal(HttpStatusCode.OK, response1.StatusCode, $"Fetching {Uri1}");
AssertX.Equal(HttpStatusCode.OK, response2.StatusCode, $"Fetching {Uri2}");
并且错误日志给出了关于哪个webapi是罪魁祸首的实际,预期和前缀。
我意识到我迟到了回答,但认为这可能有助于其他人寻找一个实用的解决方案,没有时间安装/学习另一个测试框架,只是为了从测试失败中获取有用的信息。