简体   繁体   中英

Make member public to unit-test it

I know there are many question concerning unit-tests of private members within classes. Most of them come to the conclusion that having private members that need to be tested are a design-flaw that needs refactoring (eg see here ). However I still have one last question:

When I refactor my private members to new classes they become (public) API-members however which I intended to avoid. So by simplifying our client class we polute our API by designing a new publicly visibly helper-class. Of course one might also write the test-code within the assembly and make those helpers internal but thus we´d also ship test-code to production-site.

I assume there is no right answer to this issue but perhaps you have some great ideas that help to avoid those situations?

Regarding C# there is one last trick you could try

  1. Make your class /members internal
  2. In the assembly to test, open the AssemblyInfo.cs file and make the internals visible to your Test-Project/Assembly by adding the following attribute:

[InternalsVisibleTo("YourTestProject")]

This makes you members invisible outside your assembly, except for the sake of test within the "YourTestProject"-Assembly.

More info on this Attribute can be found on MSDN .

I planned to write this as an edit but I come to the conclusion that I made whrong assumptions on the questions. I think my problem is that I mix WHAT to test with HOW to test it.

WHAT to test: members that do a certain amount of work that is worth to be tested. Access-modifier does not play any role here .

HOW to test: no problem on public members; however on private members a bit tricky, but doable as seen on nozzlemans answer above.

Having said this the correct approach would be to extract the relevant members to new non-public helper-classes . To be able to test those members although not public we use any of the previosly mentioned approaches, reflection, InternalsVisibleTo or even private accessors (which use reflection at some point).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM