如何在 VB .NET 中对单独项目中的私有函数进行单元测试?
当我开发代码时,我经常想要对类的一些构建块进行单元测试,即使它们通常是私有的。 如果我的单元测试位于项目内部,我可以使用“Friend”来完成此操作,并且仍然保持函数私有以供正常使用。 但我宁愿将我的 NUnit 测试移到他们自己的单独项目中。 我怎样才能达到我想要的效果?
As I develop code, I often want to unit test some of the building blocks of a class even if they are normally private. If my unit tests are inside the project, I can use "Friend" to accomplish this and still keep the functions private for normal use. But I would rather move my NUnit tests into their own separate project(s). How do I achieve the effect I'm looking for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法(轻松)测试来自不同项目的私有方法,但测试来自以下项目的内部方法(VB中的
Friend
)是很常见的使用InternalsVisibleToAttribute
的测试项目。 这使得Friend
成员可以被另一个程序集访问。显然这是 VB 9 中的新功能,尽管它在 C# 2 中可用...不太清楚为什么,但是 Bart de Smet 的这篇博客文章 提供了一个简单的示例。
请注意,如果您的生产程序集已签名,则您的测试程序集也需要签名,并且您必须在
InternalsVisibleToAttribute
参数中指定公钥。 有关更多详细信息,请参阅此 Stack Overflow 答案。You can't (easily) test private methods from a different project, but it's quite common to test internal methods (
Friend
in VB) from a test project usingInternalsVisibleToAttribute
. This makesFriend
members accessible to another assembly.Apparently this was new in VB 9 although it was available in C# 2... not quite sure why, but this blog post from Bart de Smet gives a quick example.
Note that if your production assembly is signed, your test assembly will need to be signed too, and you'll have to specify the public key in the
InternalsVisibleToAttribute
arguments. See this Stack Overflow answer for more details.您可以使用反射来调用私有方法。 有很多样本可以做到这一点。
You can use Reflection to invoke the private methods. There are plenty of samples out there to do this.
通过快速谷歌搜索: http://www.codeproject.com/KB/cs/ testnonpublicmembers.aspx
基础知识:(这是从上面链接的代码项目站点粘贴的)
From a quick google search: http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx
The basics: (this is pasted from the code project site linked above)