I have a nested class
and FluentAssertions can assert them.
Then I change class
to struct
and the test fails.
( If I change IEnumerable<ItemStruct> MyItems { get; set; }
to ItemStruct MyItem { get; set; }
the comparison succeeds in both cases. So I guess it has to do with the 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
compares two instances by value semantics, checking each one of it's properties if the type being compared overridesObejct.Equal
. This is not true for your value types, so they will be compared with the default equality operator for value types, which will succeed if your struct only has other struct properties but will fail when you have a reference type (IEnumerable) as one of its properties. I suspect that usingComparingByValue<DataStruct>
would solve it. – BasipetalComparingByMembers<DataStruct>()
instead. – Crustal