无法使用__exit__方法创建Mockito模拟

时间:2019-02-13 18:18:27

标签: python unit-testing mockito attributeerror contextmanager

在测试中,我无法将__exit__方法附加到模拟模仿上,以至于在with语句中使用该模拟时都不介意。

以下是不断提高AttributeError: __exit__的测试示例:

# main.py
class FooManager(object):
    def __enter__(self):
        print "Connect"
    def __exit__(self, exc_type, exc_val, exc_tb):
        print "Dissconnect"
    def foo(self):
        print "Foo"    

def function_to_be_tested(manager):
    # type: (FooManager) -> None
    with manager:
        manager.foo()
# test.py
from mockito import mock, verify, when, any as ANY

def test():
    manager_mock = mock()

    # none of this has any effect:
    manager_mock.__exit__ = lambda a, b, c: None
    when(manager_mock).__exit__(ANY(), ANY(), ANY()).thenReturn(None)

    function_to_be_tested(manager_mock)
    verify(manager_mock, times=1).foo()

解决我问题的唯一方法是:

class ContextManagerMock(mock):
    def __enter__(self):
        return None
    def __exit__(self, exc_type, exc_val, exc_tb):
        return None

def test():
    manager_mock = ContextManagerMock()
    function_to_be_tested(manager_mock)
    verify(manager_mock, times=1).foo()

但是,我想知道为什么当我尝试通过AttributeError函数或lambda函数附加__exit__方法时为什么会有一个when

1 个答案:

答案 0 :(得分:1)

您可能只是想念也需要嘲笑__enter__

In [24]: m = mock()

In [25]: when(m).__enter__(...)
Out[25]: <mockito.invocation.AnswerSelector at 0x13db478>

In [26]: when(m).__exit__(...)
Out[26]: <mockito.invocation.AnswerSelector at 0x501bd00>

In [27]: with m: ...

In [28]: verify(m).__enter__()

In [29]:

如果我不嘲笑__enter__,我会得到AttributeError: __enter__