Unit testing with network-reliant code

后端 未结 3 1269
陌清茗
陌清茗 2021-02-06 00:53

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

3条回答
  •  有刺的猬
    2021-02-06 01:29

    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:

    class LogicalDiskConsumer(object):
    
        def __init__(self, arg1, arg2, LogicalDiskFactory)
            self.arg1=arg1
            self.arg2=arg2
            self.LogicalDisk=LogicalDiskFactory()
    
        def consumedisk(self):
            self.LogicalDisk.someaction()
    

    Then in your unit test code, pass in a 'LogicalDiskFactory' that returns a mock object for the 'Win32_LogicalDisk'.

提交回复
热议问题