gol*_*enk 19 python unit-testing patch mocking typeerror
第一次使用补丁.我试图修补我的一个类进行测试.没有试图运行的补丁超过测试函数定义,但是使用补丁,测试函数定义显然需要另一个参数,我得到一个
TypeError: testAddChannelWithNamePutsChannel() takes exactly 1 argument (2 given)
Run Code Online (Sandbox Code Playgroud)
错误.测试代码如下:
import unittest
import mock
from notification.models import Channel, addChannelWithName, deleteChannelWithName
class TestChannel(unittest.TestCase):
@mock.patch('notification.models.Channel')
def testAddChannelWithNamePutsChannel(self):
addChannelWithName('channel1')
Channel.put.assert_called_with()
Run Code Online (Sandbox Code Playgroud)
为什么它需要补丁的额外参数以及该参数应该是什么?非常感谢!
ayc*_*dee 41
Patch将修补对象的实例传递给您的测试方法(如果您在类级别进行修补,则传递给每个测试方法).这很方便,因为它可以让您设置返回值和副作用,或检查所做的调用
from unittest.mock import patch
@patch('some_module.sys.stdout')
def test_something_with_a_patch(self, mock_sys_stdout):
mock_sys_stdout.return_value = 'My return value from stdout'
my_function_under_test()
self.assertTrue(mock_sys_stdout.called)
self.assertEqual(output, mock_sys_stdout.return_value)
Run Code Online (Sandbox Code Playgroud)
如果你只是想要修改一些东西来忽略它,那么你可以通过以下调用调用patch
from unittest.mock import patch, Mock
@patch('some_module.sys.stdout', Mock())
def test_something_with_a_patch(self):
Run Code Online (Sandbox Code Playgroud)
用一个对象替换sys.stdout
,并且不将它传递给方法.some_module
Mock
patch
将修补后的对象传递给测试函数.它记录在这里:
patch作为函数装饰器,为您创建模拟并将其传递给装饰函数:
Run Code Online (Sandbox Code Playgroud)>>> >>> @patch('__main__.SomeClass') ... def function(normal_argument, mock_class): ... print(mock_class is SomeClass) ... >>> function(None) True