[英]How to mock the method which was called by the method of '__init__'
My Class just like我的班级就像
import a
class Demo(object):
def __init__(self):
......
fun_return_value = a.methodB()
......
def methodA(self):
......
the test class just like below测试类就像下面
class TestDemo(test.TestCase):
def setUp(self):
super(TestDemo, self).setUp()
def test_methodA(self):
......
When I want to make methodA's unittest, there has the question that I must mock the a.methodB.But how can I do that?I checked the doc,and found nothing.当我想进行methodA的单元测试时,有一个问题是我必须模拟a.methodB。但是我该怎么做呢?我检查了文档,没有发现任何东西。 Ask others and use @mock.patch("a.methodB")
at the head of the class TestDemo.Just like问问别人,在TestDemo类的头部使用@mock.patch("a.methodB")
。就像
@mock.patch("a.methodB")
class TestDemo(test.TestCase):
def setUp(self, mock_methodB):
super(TestDemo, self).setUp()
mock_methodB.return_value=None
def test_methodA(self):
......
But it didn't work.How to mock the method which was called by the method of " init "?但是没有用。如何模拟“ init ”方法调用的方法?
has find the way to fix it.已经找到了修复它的方法。
class TestDemo(test.TestCase):
def setUp(self):
super(TestDemo, self).setUp()
self.mocks = [mock.patch('a.methodB',
mock.MagicMock(return_value=None))]
for single_mock in self.mocks:
single_mock.start()
self.addCleanup(single_mock.stop)
Patch can be used as a TestCase class decorator. Patch 可以用作 TestCase 类装饰器。 It works by decorating each test method in the class.它通过装饰类中的每个测试方法来工作。 This reduces the boilerplate code when your test methods share a common patchings set.当您的测试方法共享一个通用补丁集时,这会减少样板代码。 patch() finds tests by looking for method names that start with patch.TEST_PREFIX. patch() 通过查找以 patch.TEST_PREFIX 开头的方法名称来查找测试。 By default this is 'test'默认情况下,这是“测试”
From the docs .从文档。 That's why your code isn't working.这就是您的代码不起作用的原因。 What you can do instead is use the start and stop methods .您可以做的是使用start 和 stop 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.