1

假设我想测试这个模块:

import osutils

def check_ip6(xml):
  ib_output = osutils.call('iconfig ib0')
  # process and validate ib_output (to be unit tested)
  ...

此方法依赖于环境,因为它进行系统调用(需要特定的网络接口),因此它不能在测试机器上调用。

我想为该方法编写一个单元测试,以检查 ib_output 的处理是否按预期工作。因此我想模拟osutils.call并让它只返回测试数据。这样做的首选方法是什么?我必须做模拟或(猴子)修补吗?

示例测试:

def test_ib6_check():
    from migration import check_ib6
    # how to mock os_utils.call used by the check_ib6-method?
    assert check_ib6(test_xml) == True
4

2 回答 2

1

一种解决方案是from osutils import callyourmodule.call调用test_ib6_check.

于 2012-02-02T12:26:30.980 回答
0

好的,我发现这与模拟无关,afaik 我只需要一个猴子补丁:我需要导入并更改osutils.call-method 然后导入被测方法(而不是整个模块,因为它会导入原来的调用方法)之后。因此,此方法将使用我更改的调用方法:

def test_ib6_check():
    def call_mock(cmd):
        return "testdata"    
    osutils.call = call_mock
    from migration import check_ib6
    # the check_ib6 now uses the mocked method
    assert check_ib6(test_xml) == True
于 2012-02-02T12:44:27.847 回答