我有一个类似于此处发布的问题的问题,但目前还没有令人满意的答案:
mocking a method with another reusable method with arguments in python
Using mock patch to mock an instance method
我有以下Production类和UnitTest类。在UnitTest类的第二个测试用例中,我想用真实方法替换假方法,我在Unit Test类上面定义了这个方法。但是,我无法将被测系统中的方法even_numbers
连接到伪方法odd_numbers
,包括其输入参数。这个变种应该怎么样?我使用的是Python 2.7。
import unittest
from mock import patch
class ProdClass(object):
def even_numbers(self, numbers):
print 'This is the real method'
return [n for n in numbers if n%2 == 0]
def odd_numbers(numbers):
print 'This is the mock'
return [n for n in numbers if n%2 != 0]
class MockingTestTestCase(unittest.TestCase):
def test_even_numbers_01(self):
sut = ProdClass()
result = sut.even_numbers(range(10))
expected_result = [0, 2, 4, 6, 8]
self.assertEqual(result, expected_result,
msg = '\nRetrieved: \n{0}\nExpected: \n{1}'.format(result, expected_result))
@patch('ProdClass.even_numbers')
def test_even_numbers_02(self, mock_even_numbers):
sut = ProdClass()
'''Substitute real method even_numbers with mocked method even_numbers here'''
mock_even_numbers.return_value = odd_numbers
result = sut.even_numbers(range(10))
expected_result = [1, 3, 5, 7, 9]
self.assertEqual(result, expected_result,
msg = '\nRetrieved: \n{0}\nExpected: \n{1}'.format(result, expected_result))
if __name__ == "__main__":
unittest.main()
编辑:在下面的Martijn的帮助下,我已将代码编辑到此工作示例中:
import unittest
from mock import patch
class ProdClass(object):
def even_numbers(self, numbers):
print 'This is the real method'
return [n for n in numbers if n%2 == 0]
def odd_numbers(numbers):
print 'This is the mock'
return [n for n in numbers if n%2 != 0]
class MockingTestTestCase(unittest.TestCase):
def test_even_numbers_01(self):
sut = ProdClass()
result = sut.even_numbers(range(10))
expected_result = [0, 2, 4, 6, 8]
self.assertEqual(result, expected_result,
msg = '\nRetrieved: \n{0}\nExpected: \n{1}'.format(result, expected_result))
@patch.object(ProdClass, 'even_numbers')
def test_even_numbers_02(self, mock_even_numbers):
sut = ProdClass()
'''Substitute real method even_numbers with mocked method even_numbers here'''
mock_even_numbers.side_effect = odd_numbers
result = sut.even_numbers(range(10))
expected_result = [1, 3, 5, 7, 9]
self.assertEqual(result, expected_result,
msg = '\nRetrieved: \n{0}\nExpected: \n{1}'.format(result, expected_result))
if __name__ == "__main__":
unittest.main()