Should you Unit Test simple properties?

前端 未结 8 1373
耶瑟儿~
耶瑟儿~ 2021-02-01 13:22

Should you Unit Test simple properties of a class, asserting that a value is set and retrieved? Or is that really just unit testing the language?

Example

8条回答
  •  长情又很酷
    2021-02-01 13:25

    Generally, no. A unit test should be used to test for the functionality of a unit. You should unit test methods on a class, not individual, automatic properties (unless you are overriding the getter or setter with custom behaviour).

    You know that assigning a string value to an automatic string property will work if you get the syntax and setter value correct as that is a part of the language specification. If you do not do this then you will get a runtime error to point out your flaw.

    Unit tests should be designed to test for logical errors in code rather than something the compiler would catch anyway.

    EDIT: As per my conversation with the author of the accepted answer for this question I would like to add the following.

    I can appreciate that TDD purists would say you need to test automatic properties. But, as a business applications developer I need to weigh up, reasonably the amount of time I could spend writing and performing tests for 'trivial' code such as automatic properties compared to how long it would reasonably take to fix an issue that could arise from not testing. In personal experience most bugs that arise from changing trivial code are trivial to fix 99% of the time. For that reason I would say the positives of only unit testing non-language specification functionality outweigh the negatives.

    If you work in a fast paced, business environment which uses a TDD approach then part of the workflow for that team should be to only test code that needs testing, basically any custom code. Should someone go into your class and change the behavior of an automatic property, it is their responsibility to set up a unit test for it at that point.

提交回复
热议问题