使用 NUnit 测试属性是否为只读
我正在测试的类有一个只读属性。
public string ReadOnlyProperty
{
get { return _readOnlyProperty; }
}
有没有办法编写一个 NUnit 测试来确保该属性是只读的?我想这样做是否会让你扬起眉毛?在我看来,添加测试以确保只读属性保持只读状态(除非故意决定更改它们)与任何其他行为一样重要。
预先感谢您的反馈。
I have a read-only property on a class that I am testing.
public string ReadOnlyProperty
{
get { return _readOnlyProperty; }
}
Is there a way to write an NUnit test that ensures that this property is readonly? Does the fact that I want to do this at all cause you to raise your eyebrow? It seems to me that adding tests to ensure that read-only properties remain read-only unless a deliberate decision is made to change them is just as important as any other behavior.
Thanks in advance for the feedback.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意,但我敢说单元测试是错误的方式。原因如下:
单元测试通常用于测试代码的动态方面,即其运行时行为。另一方面,您正在寻找一种方法来测试代码的静态(编译时或设计时)方面。在我看来,FxCop 或 NDepend 等工具在这种情况下更合适。 (对于这些特定工具是否合适,我可能是错误的,因为我自己也不太了解它们。)
话虽这么说,正如您已经从之前的答案中了解到的那样,您可以使用反射来做到这一点:
I agree, but I dare say that unit testing is the wrong way. Here's why:
Unit testing is generally used to test the dynamic aspects of code, i.e. its run-time behaviour. You, on the other hand, are looking for a way to test a static (compile-time or design-time) aspect of your code. It would seem to me that tools such as FxCop or NDepend are more appropriate in this case. (I may be wrong about these particular tools being appropriate since I don't know them very well myself.)
That being said, as you've already learned from previous answers, you could do this using reflection:
您应该能够使用反射(特别是 PropertyInfo.GetSetMethod,如果没有定义 set 访问器,它将返回 null)。
You should be able to use reflection (specifically PropertyInfo.GetSetMethod, which will return null if there is no set accessor defined).