小编Die*_*emo的帖子

模拟在 with 语句中使用的类

我有一个具有__exit__and__enter__函数的类,以便我可以在 with 语句中使用它,例如:

with ClassName() as c:
    c.do_something()
Run Code Online (Sandbox Code Playgroud)

我现在正在尝试编写一个单元测试来测试这个。基本上,我试图测试do_something()只被调用过一次。

一个例子(我称之为testmocking1):

class temp:
    def __init__(self):
        pass

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    def test_method(self):
        return 1


def fun():
    with temp() as t:
        return t.test_method()
Run Code Online (Sandbox Code Playgroud)

我的测试:

import unittest
import test_mocking1
from test_mocking1 import fun
import mock
from mock import patch

class MyTestCase(unittest.TestCase):
    @patch('test_mocking1.temp', autospec = True)
    def test_fun_enter_called_once(self, mocked_object):
        fun()
        mocked_object.test_method.assert_called_once()

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

所以我希望这会通过,因为 test_method 在函数中只被调用了一次fun()。但我得到的实际结果是: …

python mocking python-2.7 python-unittest

4
推荐指数
1
解决办法
765
查看次数

标签 统计

mocking ×1

python ×1

python-2.7 ×1

python-unittest ×1