如何获得直接返回值而不是<magicmock name =“mock.xx”id =“yy”>

时间:2016-01-19 02:35:43

标签: unit-testing

这是我的测试代码:

import mock
import unittest


def check_method_return(input):
    return_value = input.ops.list()

    if not return_value:
        return False

    return return_value


def check_method_len(input):

    return_value = input.ops.list()

    if len(return_value) < 1:
        return False

    return return_value

class TestMockReturnValue(unittest.TestCase):

    def test_mock_return(self):
        fake_input = mock.MagicMock()
        fake_input().ops.list.return_value = []

        result = check_method_return(fake_input)
        self.assertFalse(result)


    def test_mock_len(self):
        fake_input = mock.MagicMock()
        fake_input().ops.list.return_value = []

        result = check_method_len(fake_input)
        self.assertFalse(result)


if __name__ == '__main__':
    test_empty = []
    if not test_empty:
        print("empty list equals to False")

    unittest.main()

运行结果输出为:

empty list equals to False
.F
======================================================================
FAIL: test_mock_return (__main__.TestMockReturnValue)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_mock.py", line 31, in test_mock_return
    self.assertFalse(result)
AssertionError: <MagicMock name='mock.ops.list()' id='140459969939728'> is not false

----------------------------------------------------------------------
Ran 2 tests in 0.005s

FAILED (failures=1)

因为当列表为空时,if的返回值为False。所以,方法&#34; check_method_return&#34;应该与&#34; check_method_len&#34;完全相同在现实世界中。

所以,我的问题是: 有没有办法让单位测试通过&#34; check_method_return&#34; ?

1 个答案:

答案 0 :(得分:0)

如果是这种情况,这是解决方案,我无法解释确切的区别,但这是有道理的:

    # this mock away input.ops.list()
    fake_input.ops.list.return_value = []


    # this did not mock away input.ops.list()
    fake_input().ops.list.return_value = []

显示设置mock_input返回值的两种方法之间的区别 这有助于更好地理解

[gliang@www ~]$ ipython
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56)
IPython 0.13.2 -- An enhanced Interactive Python.

In [1]: import unittest

In [2]: import mock

In [3]: fake_input mock.Mag
mock.MagicMixin  mock.MagicMock   mock.MagicProxy

In [4]: fake_input = mock.MagicMock()

In [5]: fake_input().ops.list.return_value= []

In [6]: print fake_input().ops.list.return_value
[]

In [7]: print fake_input.ops.list.return_value
<MagicMock name='mock.ops.list()' id='15160848'>

In [8]: fake_input2 = mock.MagicMock()

In [9]: fake_input2.ops.list.return_value = []

In [10]: print fake_input2.ops.list.return_value
[]

In [11]: quit()