模拟字符串的属性

时间:2017-10-04 21:27:37

标签: python unit-testing mocking

我想要完成的是模拟像这样的方法中的分裂

def method_separator(s):
    try:
        a, b, c = s.split('-')
        print a, b, c
    except: ValueError:
        print "An error occurred or so"

在测试中

with self.assertRaises(ValueError):
    with mock.patch(What to put here?) as mock_patch:
    mock_patch.return_value = "TEXT" # To raise ValueError
    this = method_separator('Some-good-text') # The mock should not let this good test to pass

我已经使用 string.split

进行了模拟
def method_separator(s):
    try:
        a, b, c = split.string(s, '-')
        print a, b, c
    except: ValueError:
        print "An error occurred or so"

with self.assertRaises(ValueError):
    with mock.patch('string.split') as mock_patch:
    mock_patch.return_value = "TEXT" # To raise ValueError
    this = method_separator('Some-good-text') # The mock should not let this good test to pass

即使这项工作,问题仍然存在,它是否可行?嘲笑"" .split(' - ')

的结果

1 个答案:

答案 0 :(得分:0)

要拆分的字符串将传递到您的方法中。您不需要使用patch,只需将Mock传递给方法。

# Production Code
def method_separator(s):
try:
    a, b, c = s.split('-')
    print a, b, c
except: ValueError:
    print "An error occurred or so"

# Test Code
from unittest.mock import Mock

with self.assertRaises(ValueError):
    mock_string = Mock(spec=string)
    mock_string.side_effect = ValueError("Some message")
    this = method_separator(mock_string)
当您希望您的作品通过导入语句获取模拟时,

patch非常有用。如果将值直接传递给生产代码,则必须创建自己的Mock对象。