使用 NUnit 测试属性是否为只读

发布于 2024-12-17 07:07:03 字数 254 浏览 1 评论 0原文

我正在测试的类有一个只读属性。

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

杀お生予夺 2024-12-24 07:07:03

在我看来,添加测试以确保只读属性保持只读状态(除非有意决定更改它们)与任何其他行为一样重要。

我同意,但我敢说单元测试是错误的方式。原因如下:

单元测试通常用于测试代码的动态方面,即其运行时行为。另一方面,您正在寻找一种方法来测试代码的静态(编译时或设计时)方面。在我看来,FxCop 或 NDepend 等工具在这种情况下更合适。 (对于这些特定工​​具是否合适,我可能是错误的,因为我自己也不太了解它们。)

话虽这么说,正如您已经从之前的答案中了解到的那样,您可以使用反射来做到这一点:

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

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, 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:

typeof(SomeType).GetProperty("ReadOnlyProperty").CanWrite == false
撞了怀 2024-12-24 07:07:03

您应该能够使用反射(特别是 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文