FluentAssertions 因带有枚举的结构而失败,但没有 class

FluentAssertions fails with struct with enum but not class

我有一个嵌套的 class 并且 FluentAssertions 可以声明它们。
然后我将 class 更改为 struct 并且测试失败。

(如果我将 IEnumerable<ItemStruct> MyItems { get; set; } 更改为 ItemStruct MyItem { get; set; },两种情况下的比较都会成功。所以我 猜测 它与 IEnumerable 有关。)

using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;

namespace CowsCannotReadLogs.FileHandling.UnitTest
{
    [TestClass]
    public class TestFluentAssertionStruct
    {
        public struct DataStruct
        {
            public IEnumerable<string> MyItems { get; set; }
        }

        // Fails.
        [TestMethod]
        public void TestSimpleStruct()
        {
            var data1 = new DataStruct { MyItems = new[] { "A" } };
            var data2 = new DataStruct { MyItems = new[] { "A" } };
            data1.Should().BeEquivalentTo(data2);
        }

        // Fails.
        [TestMethod]
        public void TestSimpleStructWithComparingByValue()
        {
            var data1 = new DataStruct { MyItems = new[] { "A" } };
            var data2 = new DataStruct { MyItems = new[] { "A" } };
            data1.Should().BeEquivalentTo(data2, 
                options => options.ComparingByValue<DataStruct>());
        }


        public class DataClass
        {
            public IEnumerable<string> MyItems { get; set; }
        }

        // Succeeds.
        [TestMethod]
        public void TestSimpleClass()
        {
            var data1 = new DataClass { MyItems = new[] { "A" } };
            var data2 = new DataClass { MyItems = new[] { "A" } };
            data1.Should().BeEquivalentTo(data2);
        }
    }
}

struct 上使用 BeEquivalentTo 时,这两个实例默认通过 值语义 进行比较。 要按成员比较结构,可以在本地或全局覆盖默认行为。

本地测试:

[TestMethod]
public void Test()
{
    subject.Should().BeEquivalentTo(expected, 
        opt => opt.ComparingByMembers<DataStruct>());
}

全球范围内,例如[AssemblyInitialize]:

[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
    AssertionOptions.AssertEquivalencyUsing(opt => opt.ComparingByMembers<DataStruct>());
}