在下面的简单示例中,我尝试找到一个Should()
断言,使测试通过并按照我在评论中描述的方式失败。我目前使用的那个result.ShouldBeEquivalentTo(expectedResult, o => o.RespectingRuntimeTypes())
在最后两次测试中没有失败。目标是result
和excpectedResult
应始终具有完全相同的类型和值。
using System;
using System.Linq;
using FluentAssertions;
using Xunit;
public class ParserTests
{
// The test that should be failing will be removed once the correct Should() is found
[Theory,
InlineData(DataType.String, "foo", "foo"), // should pass
InlineData(DataType.Integer, "42", 42), // should pass
InlineData(DataType.ByteArray, "1,2,3", new byte[] { 1, 2, 3 }), // should pass
InlineData(DataType.ByteArray, "1,2,3", new byte[] { 3, 2, 1 }), // should fail
InlineData(DataType.ByteArray, "1,2,3", new double[] { 1.0, 2.0, 3.0 }), // should fail, but doesn't
InlineData(DataType.Integer, "42", 42.0d)] // should fail, but doesn't
public void ShouldAllEqual(DataType dataType, string dataToParse, object expectedResult)
{
var result = Parser.Parse(dataType, dataToParse);
result.ShouldBeEquivalentTo(expectedResult, o => o.RespectingRuntimeTypes());
// XUnit's Assert seems to have the desired behavior
// Assert.Equal(result, expectedResult);
}
}
// Simplified SUT:
public static class Parser
{
public static object Parse(DataType datatype, string dataToParse)
{
switch (datatype)
{
case DataType.Integer:
return int.Parse(dataToParse);
case DataType.ByteArray:
return
dataToParse.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(byte.Parse)
.ToArray();
default:
return dataToParse;
}
}
}
public enum DataType
{
String,
Integer,
ByteArray
}
答案 0 :(得分:1)
具有等价性的东西 - 它不是平等(这是你正在尝试测试的东西)。
我能想到的唯一方法就是满足你的代码:
if (result is IEnumerable)
((IEnumerable)result).Should().Equal(expectedResult as IEnumerable);
else
result.Should().Be(expectedResult);
我没有广泛使用FluentAssertions,所以我不知道这样做的统一方法。
PS:根据我对文档的理解,RespectingRuntimeTypes()
仅影响成员在处理继承时的选择方式。