对 Class 的多个属性执行断言

Performing assertions on multiple properties of a Class

我从文档中知道我可以做到这一点...

result.Should().BeOfType<MyClass>().Which.Property1.Should().Be("String")

有没有一种方法可以测试多个属性,方式类似于

result.Should().BeOfType<MyClass>().Which.Property1.Should().Be("String").And.Property2.Should().Be(99);

如果可以执行上述任一测试而不必断言它们是什么,那也很好 'OfType' 但我怀疑代码没有其他方法可以知道哪些属性可用.

您可以针对匿名类型进行结构比较断言,如下所示:

result.ShouldBeEquivalentTo(new { Property1 = "String", Property2 = 99 }, options => options.ExcludingMissingMembers());

一个简单的解决方案是使用 BeOfType<>() 返回的 AndWhichConstraint 类型。

这就是我最终做的事情:

var myClassType = result.Should().BeOfType<MyClass>;
myClassType.Which.Property1.Should().Be("String");
myClassType.Which.Property2.Should().Be(99);