开发者

How to unit test setters on classes that do not have paired getters?

开发者 https://www.devze.com 2023-02-03 21:56 出处:网络
I\'m writing unit tests for classes which have properties that have setters but no getters. I want to be able to test these setters to make sure they are setting the data correctly.

I'm writing unit tests for classes which have properties that have setters but no getters.

I want to be able to test these setters to make sure they are setting the data correctly.

I find my options are:

  • write getters for these functions so that I can test if they are set correctly
  • write a method suc开发者_开发知识库h as testAllSetters() which test them all at once

But both solutions are undesirable since it adds unneeded functionality to the class just for the sake of testing it.

  • I could also test the output of the class to see that it is correct in general, but in many cases this doesn't test the individual setters as I would like

What is the best way to unit test setters on classes that do not have paired getters?


The problem here is that your don't want to change your API for your unit tests. Start looking at your unit tests as another user/consumer of your API. Just like developers using that library, unit tests have their own set of requirements. When you see your unit tests as consumer of your API, there will be a user that uses those getters, and it will justify them.

When this is not possible to change your API (for instance if you're developing an reusable framework), make the unit testing API internal and use the InternalsVisibleToAttribute to allow your testing library to access internal methods of your code.

Leaving unit tests aside, you still might want to consider having getters on those properties, because having properties without getters is very unintuitive for developers. The Framework Design Guidelines even have a rule against this:

DO NOT provide set-only properties or properties with the setter having broader accessibility than the getter.

You might also want to take that into consideration.

Good luck.


You could use PrivateObject to check the private members have been updated correctly after calling the setter


Do the setters have any logic?

Yes: Either open up the getter. Java: protected and have the unit test in the same package. C#: InternalsVisibleToAttribute.

No: Don't set the setters directly. No point. Test the methods that use the data set by the setters.

0

精彩评论

暂无评论...
验证码 换一张
取 消