How to write unit test hat a property that has readonly modifier on it?

ε祈祈猫儿з 提交于 2019-12-25 01:14:41

问题


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


回答1:


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.)




回答2:


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.



来源:https://stackoverflow.com/questions/6851816/how-to-write-unit-test-hat-a-property-that-has-readonly-modifier-on-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!