使用依赖网络的代码进行单元测试
我正在努力更好地对我的代码进行单元测试,但现在我正在编写大量处理远程系统的代码。 SNMP、WMI 之类的。 对于大多数类,我可以模拟对象来测试它们,但是如何处理真实系统的单元测试呢? 例如,如果我的类出去并获取服务器的 Win32_LogicalDisk 对象,我如何可能对其进行单元测试?
I'm trying to be better about unit testing my code, but right now I'm writing a lot of code that deals with remote systems. SNMP, WMI, that sort of thing. With most classes I can mock up objects to test them, but how do you deal with unit testing a real system? For example, if my class goes out and gets the Win32_LogicalDisk object for a server, how could I possibly unit test it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建一组“测试存根”来替换核心库例程并返回已知值(也许在适当的延迟之后)。
举个例子,我最近需要开发在第三方产品中运行的代码。 挑战在于我们的“合作伙伴”将进行编译并与他们的基本代码集成:我不被允许以任何形式查看他们的代码! 我的策略是构建一个非常简单的模拟器,根据他们工程师的信息,完成我认为他们的代码所做的事情。 我们使用了一种语言,可以轻松地在每个构建中切换模拟器的各个部分,因此我可以在让我们的合作伙伴构建每个新迭代之前进行大量测试。
我会再次使用相同的方法,因为该特定产品中的软件问题比我们下一个最可靠的产品中的软件问题少大约一个数量级!
You might create a set of "test stubs" that replace the core library routines and return known values, perhaps after suitable delays.
As an example, I recently needed to develop code to run inside a 3rd-party product. The challenge was that our "partner" would be doing the compiling and integration with their base code: I wasn't allowed to look at their code in any form! My strategy was to build a very simple emulator that did what I thought their code did, based on information from their engineers. We used a language that made it easy to switch various pieces of the emulator in and out of each build, so I could do a tremendous amount of testing before involving our partner to build each new iteration.
I'd use the same method again, as software problems in that particular product are about an order of magnitude fewer than in our next most reliable product!
测试难以模拟的事物的最简单方法是重构代码,使您的代码(值得测试的逻辑)位于一个位置,而代码使用的其他内容位于单独的模块中。 该模块很容易模拟,这样您就可以专注于业务逻辑。
The easiest way to test things which are hard to mock is to refactor the code in the way that your code (logic which is worth testing) is in one place and other things which your code use are in separate module(s). The module is easy to mock and this way you can focus on your business logic.
假设您的意思是“我如何测试难以/不可能模拟的事物”:
如果您有一个类“出去并获取服务器的 Win32_LogicalDisk 对象”并执行其他操作(在某些情况下消耗“Win32_LogicalDisk”对象)方式),假设您想测试使用该对象的类的各个部分,您可以使用 依赖注入 允许您模拟“Win32_LogicalDisk”对象。 例如:
然后在单元测试代码中,传入“LogicalDiskFactory”,该“LogicalDiskFactory”返回“Win32_LogicalDisk”的模拟对象。
Assuming you meant "How do I test against things that are hard/impossible to mock":
If you have a class that "goes out and gets the Win32_LogicalDisk object for a server" AND does something else (consumes the 'Win32_LogicalDisk' object in some way), assuming you want to test the pieces of the class that consume this object, you can use Dependency Injection to allow you to mock the 'Win32_LogicalDisk' object. For instance:
Then in your unit test code, pass in a 'LogicalDiskFactory' that returns a mock object for the 'Win32_LogicalDisk'.