如何从与被测类相同的模块中修补类

时间:2019-02-23 12:01:42

标签: python python-unittest

我在同一模块中定义了两个类。第二类中的方法正在调用第一类中的方法。我想在第二个方法中构造一个测试,以确认它正确地调用了第一个类,但是在使语法正确以修补该类时遇到一些问题。

以下是我拥有的代码示例:

content_provider.py:

class ContentUser():
    def getUserRef(self, username):
        ...
        return userRef

class ContentReportGeneralSearch():
    def getReport(self,username,search_text,search_type='0'):
        user = ContentUser()
        user.getUserRef(username=username)
        ....

test_content_provider.py:

@mock.patch('content_provider.ContentUser')
def test_getReport(self):
    provider = ContentReportGeneralSearch()
    provider.getReport(username='test',search_text='')
    mock_user.getUserRef.assert_called_once_with(username='test')

运行此测试时,我得到结果:

AssertionError: Expected 'getUserRef' to be called once. Called 0 times.

我怀疑问题出在指定补丁的方式上,但是我尝试了各种方式来完成补丁,但是都没有成功。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您快到了,这是单元测试解决方案:

content_provider.py

class ContentUser():
    def getUserRef(self, username):
        userRef = ''
        return userRef


class ContentReportGeneralSearch():
    def getReport(self, username, search_text, search_type='0'):
        user = ContentUser()
        user.getUserRef(username=username)

test_content_provider.py

import unittest
from unittest import mock
from content_provider import ContentReportGeneralSearch


class TestContentProvider(unittest.TestCase):
    @mock.patch('content_provider.ContentUser')
    def test_getReport(self, mock_ContentUser):
        content_user_instance = mock_ContentUser.return_value
        provider = ContentReportGeneralSearch()
        provider.getReport(username='test', search_text='')
        content_user_instance.getUserRef.assert_called_once_with(username='test')


if __name__ == '__main__':
    unittest.main()

带有覆盖率报告的单元测试结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Name                                                  Stmts   Miss  Cover   Missing
-----------------------------------------------------------------------------------
src/stackoverflow/54841363/content_provider.py            8      2    75%   3-4
src/stackoverflow/54841363/test_content_provider.py      11      0   100%
-----------------------------------------------------------------------------------
TOTAL                                                    19      2    89%

源代码:https://github.com/mrdulin/python-codelab/tree/master/src/stackoverflow/54841363