0

我有一个与此处发布的问题类似的问题,但也没有令人满意的答案:
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()
4

0 回答 0