我有一个测试类,测试方法很少,我想从测试方法中修补一些应用程序类和方法.
在pytest docs中,我找到了an example如何使用monkeypatch模块进行测试.例如,所有测试都只是函数,而不是测试类方法.
但我有一个测试方法类:
class MyTest(TestCase):
def setUp():
pass
def test_classmethod(self, monkeypatch):
# here I want to use monkeypatch.setattr()
pass
只是通过monkeypatch作为方法参数显然是行不通的.所以看起来像py.test魔法不能这样工作.
所以问题很简单,也许是愚蠢的:如何在测试类方法中使用monkeypatch.setattr()进行pytest?
解决方法:
它以这种形式can’t work
While pytest supports receiving fixtures via test function arguments
for non-unittest test methods, unittest.TestCase methods cannot
directly receive fixture function arguments as implementing that is
likely to inflict on the ability to run general unittest.TestCase test
suites.
您可以直接创建monkeypatch
from _pytest.monkeypatch import MonkeyPatch
class MyTest(TestCase):
def setUp():
self.monkeypatch = MonkeyPatch()
def test_classmethod(self):
self.monkeypatch.setattr ...
...
或者创建自己的fixture,它会将monkeypatch添加到你的类中,并使用@ pytest.mark.usefixtures
@pytest.fixture(scope="class")
def monkeypatch_for_class(request):
request.cls.monkeypatch = MonkeyPatch()
@pytest.mark.usefixtures("monkeypatch_for_class")
class MyTest(TestCase):
def setUp():
pass
def test_classmethod(self):
self.monkeypatch.setattr ...
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。