【发布时间】:2018-08-09 18:40:17
【问题描述】:
如何比较具有相同名称但不同类型的属性的对象?
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:
void Main()
{
A a = new A { Id = Guid.NewGuid() };
B b = Map(a);
b.Should().BeEquivalentTo(a);
}
这会产生以下错误:
AssertionFailedException:预期成员 ID 为 {ff73e7c7-21f0-4f45-85fa-f26cd1ecafd0},但找到“{ff73e7c7-21f0-4f45-85fa-f26cd1ecafd0}”。
文档建议自定义属性断言规则可以使用Equivalence Comparison Behavior
第 2 版:
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>());
}
但如果属性不属于同一类型,则会产生运行时异常。
AssertionFailedException:预期的来自主题的成员 ID 是 System.Guid,但找到了 System.String。
有什么想法吗?
【问题讨论】:
标签: c# unit-testing fluent-assertions