如何在单元测试中使用Python模拟

时间:2015-02-11 16:47:24

标签: python python-2.7 python-unittest python-mock

关于Python模拟的大多数建议都是在单元测试框架之外的简短片段中提供的。这个可行的发现,我试图遵循这个建议,但是一旦我将它嵌入适当的单元测试中它就不会成功。例如,此代码在结尾处的注释中生成输出:

# foo.py
def some_fn():
    return 'some_fn'

class Foo( object ):
    def method_1( self ):
        return some_fn()

# bar.py (depends on foo.py)
import foo
class Bar( object ):
    def method_2( self ):
        tmp = foo.Foo()
        return tmp.method_1()

# test.py (tests bar.py)
import unittest
import bar
from mock import patch

class Test( unittest.TestCase ):
    def setUp( self ):
        pass
    def tearDown( self ):
        pass

    @patch( 'foo.some_fn' )
    def test_bar( self, mock_some_fn ):
        mock_some_fn.return_value = 'test-val-1'
        tmp = bar.Bar()
        print tmp.method_2()
        self.assertEqual( tmp.method_2(), 'test-val-1' )  # line 32
        mock_some_fn.return_value = 'test-val-2'
        self.assertEqual( tmp.method_2(), 'test-val-2' )

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

我在PyDev中运行并看到:

Finding files... done.
Importing test modules ... done.

some_fn
======================================================================
FAIL: test_bar (test.foo.all.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/mock.py", line 1201, in patched
    return func(*args, **keywargs)
  File "/home/russ/dev/workspace/python-mocking/test/foo/all.py", line 32, in test_bar
    self.assertEqual( tmp.method_2(), 'test-val-1' )
AssertionError: 'some_fn' != 'test-val-1'

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (failures=1)

删除单元测试框架,此代码运行正常(此处,只是整个文件的 test.py 部分):

...
# test.py (tests bar.py)
import bar
from mock import patch

@patch( 'foo.some_fn' )
def test_bar( mock_some_fn ):
  mock_some_fn.return_value = 'test-val-1'
  tmp = bar.Bar()
  print tmp.method_2()
  assert tmp.method_2() == 'test-val-1'
  mock_some_fn.return_value = 'test-val-2'
  assert tmp.method_2() == 'test-val-2'

成功生成,运行时:

~/dev/workspace/python-mocking/test/foo $ python
Python 2.7.5 (default, Nov  3 2014, 14:26:24) 
...
>>> import all0
>>> all0.test_bar()
test-val-1

我必须做些什么来使其在单元测试框架中表现出来?

1 个答案:

答案 0 :(得分:0)

对我来说,Python和PyDev新手的答案是,这是一个PyDev问题。 PyDev似乎对如何设置项目的单元测试非常敏感。我成功编写了一个与此完全相同的新项目,包括单独的文件,使这个代码成功。

python-mocking
+-- mocking_example
    +-- test
    |   +-- __init__.py
    |   `-- test.py
    +-- __init__.py
    +-- bar.py
    `-- foo.py

值得注意的是,上面的结构使得在 test.py 中必须导入bar:

import mocking_example.bar

以这种方式消费,即:

tmp = mocking_example.bar.Bar()