简体   繁体   English

如何在Visual Studio(VB.Net和C#)中对私有功能进行单元测试?

[英]How can I do unit testing for private function in Visual Studio (VB.Net and C#)?

I know it may sound like a silly question as I've heard many saying that you should only do unit testing for public function and indeed, visual basic.net in Visual studio IDE only allows me to do unit testing for public function. 我知道这听起来像是个愚蠢的问题,因为我听到很多人说您应该只对公共功能进行单元测试,而实际上,Visual Studio IDE中的visual basic.net只允许我对公共功能进行单元测试。

However, I got a public function that is calling to many other private functions. 但是,我有一个公共函数正在调用许多其他私有函数。 If I do unit testing for that public function, that would be too complicated. 如果我对该公共功能进行单元测试,那就太复杂了。 I only want to test each private function individually to make sure it works correctly first, before jumping to the parent public function. 我只想单独测试每个私有函数,以确保在跳到父公共函数之前先正确工作。

One solution I've had in my mind is that I could change all private functions to public ones so that Visual Studio allows me to do unit testing for them. 我想到的一种解决方案是,我可以将所有私有功能更改为公共功能,以便Visual Studio允许我对其进行单元测试。 But it is annoying me as I don't want them to be public. 但这让我很烦,因为我不想让他们公开。

Is there any suggestions you could let me know please? 有什么建议可以让我知道吗?

many thanks in advance. 提前谢谢了。

NTC NTC

If you really can't break the code out into separate classes, you could change all of the private functions to be protected and then create a private class within your test class that inherits from the class you're trying to test (this would be named as a fake or stub, hence my advice to make it private. You don't want code outside of the test class to interact with this). 如果您确实无法将代码分成单独的类,则可以更改所有要保护的私有函数,然后在测试类中创建一个私有类,该私有类继承自您要测试的类(这是名称为伪造或存根,因此我建议将其设为私有。您不希望测试类外部的代码与此进行交互)。 Within your inherited class, create public functions for each of the now protected functions that simply call through to the base and write your unit tests against those instead. 在继承的类中,为每个现在受保护的函数创建公共函数,这些函数只需调用基本函数,然后针对这些函数编写单元测试即可。

I apologize if this capability is not available in VB: 对于此功能在VB中不可用,我深表歉意:

Create a sub-class of the class you want to test. 创建您要测试的类的子类。 Ensure that the sub-class has public interfaces to the private functions. 确保子类具有到私有功能的公共接口。

As for "only unit test public functions?" 至于“仅单元测试公共功能?” That's horse manure. 那是马粪。 You test what might fail. 您测试什么可能失败。 For instance, you might have a class with only one public function, and you want to refactor into a set of calls on private functions to decrease the complexity. 例如,您可能有一个仅包含一个公共函数的类,并且您希望将其重构为一组对私有函数的调用以降低复杂性。 If you have to refactor your solution for any reason (as one of the comments suggested), then the first step is to have all the pieces of the solution tested that you will have to change during the refactoring. 如果您由于某种原因不得不重构解决方案(如建议的其中一项建议),那么第一步就是对解决方案的所有部分进行测试,以便在重构期间进行更改。

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

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