如何在 .NET 中循环并测试已实例化对象的属性值
已经用谷歌搜索了这个问题,所以如果答案就在这里或者相当简单,我深表歉意。
我正在编写单元测试。在这个特定的例子中,我使用无参数构造函数实例化一个对象。使用该构造函数实例化时,不会设置其任何属性。
然后,作为测试的一部分,我想要“循环”属性并断言它们是“null”、“0”或“false”(这将是正确的状态)。
我知道这听起来像是一件愚蠢的事情,但如果我能做到这一点,那么我就可以为其他一切编写更高效、更可读的测试。
我知道我可以“循环”“类型”的属性,但这不是“类型”的实例化对象。它是一个“类型”对象。
在我看来,它应该是(但显然不是)以下内容:
var target = new MyObject();
foreach(var property in target.GetProperties())
{
Assert.IsNull(property);
}
有人吗?
have "Googled the cr*p" out of this one so apologies if the answer is either on here, or fairly simple.
I am writing Unit tests. In this particular one I am instantiating an object using a parameterless constructor. When instantiating using that constructor none of its properties will be set.
I then, as part of the test, want to "loop" through the properties and assert that they are either "null", "0" or "false" (which would be the correct state).
I know it sounds like a dumb thing to do, but if I can do this, then I can write more efficient and readable tests for everything else.
I know I can "loop" through the properties of a "Type", but that's not an instantiated object "of type". It's a "Type" object.
In my head it should be (but obviously isn't) the following:
var target = new MyObject();
foreach(var property in target.GetProperties())
{
Assert.IsNull(property);
}
Anyone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您循环遍历该类型的属性,然后针对该类型的实例查找每个属性的值:
You loop through the properties of the type, and then find the value of each property against an instance of the type: