我在线阅读了很多关于嘲笑整个课程的信息。但是,我有一个有多种方法的课程;例如:
class A():
def methoda(param1, param2):
do things
return thing
def methodb(param3):
do things (including something calling methoda)
如何在测试文件中模拟methoda以返回所需的值,以便我可以测试methodb?我不想嘲笑整个班级。
我尝试过做的事情:
from mock import patch, mock, MagicMock
from sourceA.models import ClassName
from django.test import TestCase
class ClassTest(TestCase):
@patch('sourceA.models.ClassName.methodA')
def test_method(self, mock_method_return):
mock_method_return.return_value = 10
instance = ClassName()
instance.methodB #METHOD B CALLS METHOD A; I want method A to return 10
print "OUTPUT", instance.FIELDA #Debug Tool - Field A is modified by Method B, based on the return value of method A
assert instance.FIELDA == 10
我也试过这个:
class ClassTest(TestCase):
@patch('sourceA.models.ClassName.methodA', return_value=10)
def test_method(self, mock_method_return):
instance = Mock(spec=ClassName())
instance.methodB #METHOD B CALLS METHOD A; I want method A to return 10
------ OR instance methodB = MagicMock(return_value=10) and then instance.MethodB
print "OUTPUT", instance.FIELDA #Debug Tool - Field A is modified by Method B, based on the return value of method A
self.assertEqual(instance.FIELDA, 10)
我不确定我还应该尝试什么/我做错了什么。