我想弄清楚在我的測試中使用autospec的最佳方法。在下面的場景中,我使用autospec來檢測何時調用過多的參數。如果使用$ python filename.py
調用,此場景按預期工作。當調用過少的參數時Autospec不失敗
import unittest
import mock
class FakeDependency(object):
def set_obj(arg1, arg2):
self.foo = arg1
self.bar = arg2
class FakeObject(object):
def __init__(self):
self.fake_dependency = FakeDependency()
def set_dependency(self):
self.fake_dependency.set_obj('foo', 'bar', 'buz') # Bug
class TestFakeObject(unittest.TestCase):
@mock.patch.object(FakeDependency, 'set_obj')
def test_set_dependency_with_assert_called(self, mock_dependency):
r = FakeObject()
r.set_dependency()
mock_dependency.assert_called_once_with('foo', 'bar', 'buz') # Test passes does not catch bug
@mock.patch.object(FakeDependency, 'set_obj', autospec=True)
def test_set_dependency_with_autospec(self, mock_dependency):
r = FakeObject()
r.set_dependency() # Test Fails
if __name__ == '__main__':
unittest.main()
但是,如果我改變測試用例來檢測太少ARG遊戲時調用然後將其傳遞並沒有趕上錯誤。
class FakeDependency(object):
def set_obj(arg1, arg2, arg3):
self.foo = arg1
self.bar = arg2
self.buz = arg3
class FakeObject(object):
def __init__(self):
self.fake_dependency = FakeDependency()
def set_dependency(self):
self.fake_dependency.set_obj('foo', 'bar') # Bug
class TestFakeObject(unittest.TestCase):
@mock.patch.object(FakeDependency, 'set_obj')
def test_set_dependency_with_assert_called(self, mock_dependency):
r = FakeObject()
r.set_dependency()
mock_dependency.assert_called_once_with('foo', 'bar') # Test passes does not catch bug
@mock.patch.object(FakeDependency, 'set_obj', autospec=True)
def test_set_dependency_with_autospec(self, mock_dependency):
r = FakeObject()
r.set_dependency() # Test Also passes
所以我的問題是做什麼錯了?根據doc,autospec也應該檢測何時通過的參數太少。
我剛剛運行它使用python filename.py – Dan
@sxn這是我的問題,當我改變了調用python -m unittest文件名,它按預期工作。 – Dan