C# 当属性的类型不同时,FluentAssertions-Should().beeEquivalento()
如何比较具有相同名称但不同类型属性的对象C# 当属性的类型不同时,FluentAssertions-Should().beeEquivalento(),c#,unit-testing,fluent-assertions,C#,Unit Testing,Fluent Assertions,如何比较具有相同名称但不同类型属性的对象 public class A { public Guid Id { get; set; } } public class B { public string Id { get; set; } } public static B Map(A a){ return new B { Id = a.Id.ToString() }; } 第1版: 这会产生以下错误: AssertionFailedException:预期成员Id为{f
public class A
{
public Guid Id { get; set; }
}
public class B
{
public string Id { get; set; }
}
public static B Map(A a){
return new B { Id = a.Id.ToString() };
}
第1版:
这会产生以下错误:
AssertionFailedException:预期成员Id为{ff73e7c7-21f0-4f45-85fa-f26cd1ecafd0},但找到“{ff73e7c7-21f0-4f45-85fa-f26cd1ecafd0}”
文档表明,可以使用
第2版:
void Main()
{
A=新A{Id=Guid.NewGuid()};
B=地图(a);
b、 应()相当于(a,
选项=>选项
.Using(ctx=>ctx.Subject.Should().Be(ctx.Expectation))
.WhenTypeIs());
}
但如果属性不属于同一类型,则会生成运行时异常
AssertionFailedException:预期subject中的成员Id为System.Guid,但找到System.String
有什么想法吗?这里有两种方法可以比较具有相同名称的不同类型成员的对象 第一种方法是指定名为
Id
A expected = new A { Id = Guid.NewGuid() };
B actual = Map(expected);
actual.Should().BeEquivalentTo(expected,
options => options
.Using<object>(ctx => ctx.Subject.Should().Be(ctx.Expectation.ToString()))
.When(info => info.SelectedMemberPath.EndsWith("Id")));
这是一个开放的概念。应该将DifferentingObjectSequivalencyStep作为扩展方法添加到fluentassertions中@MichalCiechan可以在网上自由发表一篇文章。我目前正在使用另一种方法编写
。使用(ctx=>ctx.Subject.Should().be(ctx.Expectation.ToString())。当(info=>info.SelectedMemberPath.EndsWith(“Id”))
。这应该不那么脆弱,更具表现力。
void Main()
{
A a = new A { Id = Guid.NewGuid() };
B b = Map(a);
b.Should().BeEquivalentTo(a,
options => options
.Using<Guid>(ctx => ctx.Subject.Should().Be(ctx.Expectation))
.WhenTypeIs<Guid>());
}
A expected = new A { Id = Guid.NewGuid() };
B actual = Map(expected);
actual.Should().BeEquivalentTo(expected,
options => options
.Using<object>(ctx => ctx.Subject.Should().Be(ctx.Expectation.ToString()))
.When(info => info.SelectedMemberPath.EndsWith("Id")));
AssertionOptions.AssertEquivalencyUsing(c =>
c.Using(new DifferentObjectsEquivalencyStep<A, B>(Map)));
A expected = new A { Id = Guid.NewGuid() };
B actual = Map(expected);
actual.Should().BeEquivalentTo(expected);