简体   繁体   English

使成员公开以对其进行单元测试

[英]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. 当我将私有成员重构为新类时,它们将成为(公共)API成员,但是我希望避免这种情况。 So by simplifying our client class we polute our API by designing a new publicly visibly helper-class. 因此,通过简化客户端类,我们通过设计一个新的公开可见的帮助程序类来污染我们的API。 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 关于C#,您可以尝试的最后一招

  1. Make your class /members internal 使您的class /成员成为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: 在要测试的程序集中,打开AssemblyInfo.cs文件,并通过添加以下属性使内部零件对您的Test-Project / Assembly可见:

[InternalsVisibleTo("YourTestProject")]

This makes you members invisible outside your assembly, except for the sake of test within the "YourTestProject"-Assembly. 除了在“ YourTestProject” -Assembly中进行测试之外,这使您的成员在程序集外部不可见。

More info on this Attribute can be found on MSDN . 可以在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). 为了能够测试那些成员(尽管不是公共成员),我们使用了任何之前提到的方法,反射, InternalsVisibleTo私有访问器 (有时使用反射)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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