第一次使用补丁。我尝试修补我的一个类以进行测试。如果没有尝试运行的补丁程序,则会通过测试函数定义,但是使用补丁程序,测试函数定义显然需要另一个参数,我得到了一个
TypeError: testAddChannelWithNamePutsChannel() takes exactly 1 argument (2 given)错误。测试代码如下:
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()为什么补丁需要一个额外的参数?这个参数应该是什么?非常感谢!
发布于 2013-04-17 15:03:21
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)如果您只是想从字面上修补一些东西以忽略它,那么您可以使用以下调用来调用patch
from unittest.mock import patch, Mock
@patch('some_module.sys.stdout', Mock())
def test_something_with_a_patch(self):这会将some_module中的sys.stdout替换为Mock对象,而不会将其传递给该方法。
发布于 2013-04-17 13:14:25
patch将修补后的对象传递给测试函数。它的文档here
作为函数装饰器的
补丁,为您创建模拟并将其传递到装饰过的function:@patch('__main__.SomeClass')中……def函数(normal_argument,mock_class):...True
(Mock_class is SomeClass) ... >>>函数(无)打印
https://stackoverflow.com/questions/16051422
复制相似问题