英文:
Common mocks defined with @patch to several test case functions in Python
问题
我有这个使用模拟(简化版)的Python测试代码:
from unittest import TestCase
from mock import patch
class TestClass(TestCase):
@patch("mymodule.function1")
@patch("mymodule.function2")
@patch("mymodule.function3")
def test_case_1(self, function3_mock, function2_mock, function1_mock):
# test_case_1的代码
...
@patch("mymodule.function1")
@patch("mymodule.function2")
@patch("mymodule.function3")
def test_case_2(self, function3_mock, function2_mock, function1_mock):
# test_case_2的代码
...
@patch("mymodule.function1")
@patch("mymodule.function2")
@patch("mymodule.function3")
def test_case_3(self, function3_mock, function2_mock, function1_mock):
# test_case_3的代码
...
我想知道是否有一种方法可以简化这个,以便:
- 我不需要在每个测试用例函数中重复三个
@patch(...)
语句 - 我不需要将模拟函数传递给测试用例函数,这样我可以只写
def test_case_1(self)
,例如
是否可能?你能提供一些提示/建议吗?
提前谢谢!
英文:
I have this testing code in Python using mocks (simplified):
from unittest import TestCase
from mock import patch
class TestClass(TestCase):
@patch("mymodule.function1")
@patch("mymodule.function2")
@patch("mymodule.function3")
def test_case_1(self, function3_mock, function2_mock, function1_mock):
# code for test_case_1
...
@patch("mymodule.function1")
@patch("mymodule.function2")
@patch("mymodule.function3")
def test_case_2(self, function3_mock, function2_mock, function1_mock):
# code for test_case_2
...
@patch("mymodule.function1")
@patch("mymodule.function2")
@patch("mymodule.function3")
def test_case_3(self, function3_mock, function2_mock, function1_mock):
# code for test_case_3
...
...
I wonder if there is some way of simplifying this, so:
- I don't repeat all the time the three
@patch(...)
statements in each test case function - I don't need to pass the mock function to the test case function, so I can call write just
def test_case_1(self)
for instance
Is that possible? Could you provide some hints/advice?
Thanks in advance!
答案1
得分: 0
以下是翻译好的内容:
以这种方式重构可以实现两个目标:
from unittest import TestCase
from mock import patch, Mock
function1_mock = Mock()
function2_mock = Mock()
function3_mock = Mock()
@patch("mymodule.function1", function1_mock)
@patch("mymodule.function2", function2_mock)
@patch("mymodule.function3", function3_mock)
class TestClass(TestCase):
def test_case_1(self):
# test_case_1 的代码
...
def test_case_2(self):
# test_case_2 的代码
...
def test_case_3(self):
# test_case_3 的代码
...
...
英文:
Refactored this way achieves both objectives:
from unittest import TestCase
from mock import patch, Mock
function1_mock = Mock()
function2_mock = Mock()
function3_mock = Mock()
@patch("mymodule.function1", function1_mock)
@patch("mymodule.function2", function2_mock)
@patch("mymodule.function3", function3_mock)
class TestClass(TestCase):
def test_case_1(self):
# code for test_case_1
...
def test_case_2(self):
# code for test_case_2
...
def test_case_3(self):
# code for test_case_3
...
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论