c#:调试时为 public,否则为 private
有没有一种好的方法可以使函数在我使用 NUnit 测试时是公共的,而在其他情况下是私有的?
不必生成大量无关代码也很好。
------------------------编辑------------------------
它似乎解决方案分为三种类型:
- 不要做我想做的事。
- 使用编译器指令。
- 尝试一个聪明的解决方案(比如使用 内部可见)。
有没有办法以编程方式执行此操作?即只需创建一个新的临时应用程序,使所有protected/private/internal
函数成为public
,将其插入 NUnit,在那里运行测试,然后返回使用 private发布版本的功能?
Is there a nice way to make it so that functions are public when I am testing with NUnit, but private otherwise?
Not having to generate a lot of extraneous code would also be nice.
------------------------Edit------------------------
It seems the solutions fall under 3 types:
- don't do what I'm attempting to do.
- use compiler directives.
- try a clever solution (like using
InternalsVisibleTo).
Might there be a way to do this programmatically? i.e. just create a new temporary app that makes all protected/private/internal
functions public
, plug that into NUnit, run the tests there, and then go back to using the private functions for the release version?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用
private
<->public
将它们设置为internal
<->public
,而不是private
<->public a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" rel="noreferrer">InternalsVisibleTo
。InternalsVisibleTo
是一个程序集属性,您可以在要使其对单元测试程序集可见的程序集中使用它。您必须对单元测试程序集进行签名,因为InternalsVisibleTo
属性依赖于调用程序集的公钥。Instead of
private
<->public
you can make theminternal
<->public
usingInternalsVisibleTo
.InternalsVisibleTo
is an assembly attribute that you can use in the assembly you want to make visible to your unit test assembly. You will have to sign your unit test assembly, because theInternalsVisibleTo
attribute relies on the public key of the calling assembly.如果您对调用私有方法的公共方法有很好的了解,您可能不需要这样做,但这似乎是另一场争论。
这是一个关于 TDD 及其不同方法的很好的链接:
如何在 .NET 中测试私有方法和受保护方法
You might not need to if you have good coverage on your public methods which call the private methods but that seems to be another debate into it self.
This is a good link about TDD and different ways to do it:
How to Test Private and Protected methods in .NET
正如其他人指出的那样,总是有
internal
,但由于它与private
和public
不同(因此可能会影响同一程序集中的其他代码) ),为什么不使用编译器指令:There's always
internal
as others have pointed out, but since that's distinct from bothprivate
andpublic
(and hence could affect other code in the same assembly), why not use compiler directives:测试方法Tested()
Test MethodTested()
试试这个:
Try this:
很快,试试这个:
usa as myMethod();
Shortly, try this:
usa as myMethod();