我有一个嵌套的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);
}
}
}
最佳答案
在BeEquivalentTo
上使用struct
时,默认情况下会通过值语义比较这两个实例。
要比较其成员的结构,可以在本地或全局覆盖默认行为。
在测试内部:
[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>());
}