如何编写具有 readonly 修饰符的属性的单元测试?
这可能是一个愚蠢的问题
public class File
{
public Metadata metadata
{
get
{
return _metadata;
}
}
private readonly Metadata _metadata;
#region public
File () { ... }
Foo () { ... }
#endregion
}
现在我想知道是否需要编写单元测试来验证 _metadata 是只读的情况,以及如何
this might be a stupid question
public class File
{
public Metadata metadata
{
get
{
return _metadata;
}
}
private readonly Metadata _metadata;
#region public
File () { ... }
Foo () { ... }
#endregion
}
Now I am wondering whether I need to write unit tests to verify the case that the _metadata is readonly, and how
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,您通常不需要为编译器声明和检查的内容编写测试。例如,您通常不会编写只能调用具有正确类型的方法等的测试。
当然,如果您有多种类型并且您想要检查它们的所有属性是否都是只读的,那么这是有意义的。 (例如“此接口的每个实现都应该是不可变的” - 只读属性至少是检查这一点的开始。)
No, you don't generally need to write tests for things which are declared to and checked by the compiler. For example, you don't generally write tests that you can only call methods with the right types, etc.
Of course, if you have several types and you want to check that all their properties are readonly, for example, that makes sense. (e.g. "every implementation of this interface should be immutable" - readonly properties is at least a start to checking that.)
除了 Jon Skeet 的回答之外,单元测试应该只测试类的公共契约,而不应该探究它的内部工作原理(以使重构更容易)。
这里的实现让我担心,因为我可以看到契约文件的元数据应该是只读的。假设元数据具有公共属性和/或改变属性的公共方法,那么人们可以通过访问来更改文件的元数据
metadata
属性,并且违反了德米特定律,调用其方法/更改其属性。In addition to Jon Skeet's answer, unit testing should only test the public contract of the class and shouldn't probe the inner workings of it (to make refactoring easier).
The implementation here worries me because I could see the contract being File's Metadata should be read-only. Assuming Metadata has public properties and/or public methods that alter properties, then one can change a File's Metadata by accessing the
metadata
property and, in violation of the Law of Demeter, calling methods/changing properties on it.