简体   繁体   English

使用NUnit测试属性为只读

[英]Testing that a property is read-only using 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? 有没有一种方法可以编写NUnit测试来确保此属性为只读? 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. 在此先感谢您的反馈。

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. 在我看来,添加测试以确保只读属性保持只读(除非做出了有意更改它们的决定)与任何其他行为一样重要。

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, ie 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. 在我看来,像FxCop或NDepend这样的工具在这种情况下更合适。 (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: 话虽如此,您已经从先前的答案中学到了,您可以使用反射做到这一点:

typeof(SomeType).GetProperty("ReadOnlyProperty").CanWrite == false

您应该能够使用反射(特别是PropertyInfo.GetSetMethod,如果未定义集合访问器,它将返回null)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM