【问题标题】:Assert that two objects are exactly equivalent断言两个对象完全等价
【发布时间】:2016-03-04 11:42:39
【问题描述】:

在下面的简单示例中,我尝试找到一个 Should() 断言,它使测试通过并失败,就像我在 cmets 中描述的那样。我目前使用的result.ShouldBeEquivalentTo(expectedResult, o => o.RespectingRuntimeTypes()) 在最后两个测试中没有失败。目标是 resultexcpectedResult 应该始终具有完全相同的类型和值。

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
}

【问题讨论】:

  • ShouldBeEquivalentTo(...) 的代码是什么?
  • 那不是我的代码,那是 FluentAssertions (github.com/dennisdoomen/fluentassertions) 的代码。这是一个关于 FluentAssertions 的问题。

标签: c# xunit.net fluent-assertions


【解决方案1】:

这就是 Equivalency 的问题 - 它不是 Equality(这是您要测试的内容)。

我能想到的满足您的代码的唯一方法是:

if (result is IEnumerable)
    ((IEnumerable)result).Should().Equal(expectedResult as IEnumerable);
else
    result.Should().Be(expectedResult);

我没有广泛使用 FluentAssertions,所以我不知道这样做的统一方法。

PS:根据我对文档的理解,RespectingRuntimeTypes() 只影响在处理继承时选择成员的方式。

【讨论】:

    猜你喜欢
    • 2022-05-01
    • 2022-04-20
    • 2010-12-16
    • 2014-06-25
    • 2016-01-05
    • 2019-03-28
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    相关资源
    最近更新 更多