Using “friend”-declarations for unit testing. Bad idea?

前端 未结 5 1884
情书的邮戳
情书的邮戳 2020-12-30 02:28

[Of course, the question is not restricted to a specific \"friend\" implementation, feel free though to point out implementation specifics if relevant]

Read

5条回答
  •  生来不讨喜
    2020-12-30 03:20

    I've made extensive use of this technique - it means that my unit tests can test aspects of the code library that aren't visible to normal consumers.

    While using [InternalsVisibleTo] does increase coupling, I believe the (minor) increase is well worth the gains.

    My unit tests are already tightly coupled to the code under test - though I try to write tests that assure specific outcomes, not specific implementations, by accessing things not visible to regular consumers, I do somewhat constrain the implementation.

    Going the other way, the coupling is minimal - in having the [InternalsVisibleTo] attribute on the code assembly, and in marking some things as internal instead of private (or protected internal instead of protected).

    (Note that I'm ignoring here any design changes that are provoked by the use of Unit Testing, which is a whole other discussion.)

    The [InternalsVisibleTo] attribute requires strong naming your assemblies. If you're not doing this already, you may find this a bit burdensome as a strongly named assembly may only depend on other strongly named assemblies, which may end up with you needing to alter several assemblies.

    Getting the attribute right can be a bit fiddly, as it needs to include the public key of your test assembly. IDesign have a useful Friend Assembly tool that creates the attribute on your clipboard, ready for pasting. Recommended.

提交回复
热议问题