使用依赖网络的代码进行单元测试 [英] Unit testing with network-reliant code
问题描述
我正在努力更好地对我的代码进行单元测试,但现在我正在编写大量处理远程系统的代码.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?
推荐答案
假设您的意思是我如何针对难以/不可能模拟的事物进行测试":
Assuming you meant "How do I test against things that are hard/impossible to mock":
如果您有一个类出去并获取服务器的 Win32_LogicalDisk 对象"并执行其他操作(以某种方式使用Win32_LogicalDisk"对象),假设您想测试使用此对象的类的各个部分对象,您可以使用 Dependency Injection 来模拟 'Win32_LogicalDisk' 对象.例如:
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:
class LogicalDiskConsumer(object):
def __init__(self, arg1, arg2, LogicalDiskFactory)
self.arg1=arg1
self.arg2=arg2
self.LogicalDisk=LogicalDiskFactory()
def consumedisk(self):
self.LogicalDisk.someaction()
然后在您的单元测试代码中,传入一个LogicalDiskFactory",它返回一个Win32_LogicalDisk"的模拟对象.
Then in your unit test code, pass in a 'LogicalDiskFactory' that returns a mock object for the 'Win32_LogicalDisk'.
这篇关于使用依赖网络的代码进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!