3

当一个方法应该在测试用例中被模拟时,可以在 python框架中应用@mock.patch装饰器(参见1):unittest

    class MyTest(TestCase):
        @patch('method2')
        @patch('method1')
        def test_stuff(self, mock_method1, mock_method_2):
            ...

根据文档2,也可以将 应用@mock.patch为类装饰器:

    @patch('method2')
    @patch('method1')
    class MyTest(TestCase):
        def test_stuff(self, mock_method_1, mock_method_2):
            ...

因此,将这两种方法结合起来也应该是可能和合理的:

    @patch('method1')
    class MyTest(TestCase):
        @patch('method2')
        def test_stuff(self, mock_method_A, mock_method_B):
            ...

现在我想知道模拟以什么顺序传递给test_stuff. mock_method_A模拟method1or也是如此method2

4

1 回答 1

2

方法装饰器的模拟在类装饰器之前应用。即 mock_method_A是模拟method2mock_method_B是模拟method1

请参阅此自包含示例以进行说明:

from unittest import TestCase, main, mock


def method1():
    return 1


def method2():
    return 2


@mock.patch('test.method2', return_value='method2')
@mock.patch('test.method1', return_value='method1')
class TestClassDecoratorOrder(TestCase):
    def test_order(self, mock_method1, mock_method2):
        self.assertEqual(mock_method1(), 'method1')
        self.assertEqual(mock_method2(), 'method2')


class TestMethodDecoratorOrder(TestCase):
    @mock.patch('test.method2', return_value='method2')
    @mock.patch('test.method1', return_value='method1')
    def test_order(self, mock_method1, mock_method2):
        self.assertEqual(mock_method1(), 'method1')
        self.assertEqual(mock_method2(), 'method2')


@mock.patch('test.method2', return_value='method2')
class TestCombinedDecoratorOrder(TestCase):
    @mock.patch('test.method1', return_value='method1')
    def test_order(self, mock_method1, mock_method2):
        self.assertEqual(mock_method1(), 'method1')
        self.assertEqual(mock_method2(), 'method2')


if __name__ == "__main__":
    main()

于 2020-03-03T10:14:20.883 回答