我遇到了同样的问题。我有一个测试,它从两个 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 是罪魁祸首。
我意识到我回答迟了,但认为这可能有助于其他人寻找实用的解决方案,而这些解决方案没有时间安装/学习另一个测试框架,只是为了从测试失败中获取有用的信息。