My project structure:
├── core
| └── service
| └── file.py
└── tests
└── test_file.py
I have a function fun
that uses a class method.
file.py
from another_module import myClass
cls_instance=myClass()
def fun():
return cls_instance.request()
And I want to test the function fun
by patch as showed below:
test_file.py
from core.service.file import fun
class TestCase(unittest.TestCase):
@patch("core.service.file.cls_instance")
def setUp(self, mock):
self.mock = mock.return_value
def test_fun(self):
self.mock.request.return_value = 1
resp=fun()
self.assertEqual(resp, 1)
Test Failed with the message:
Expected : None
Actual : 1
What am I doing wrong here?
My project structure:
├── core
| └── service
| └── file.py
└── tests
└── test_file.py
I have a function fun
that uses a class method.
file.py
from another_module import myClass
cls_instance=myClass()
def fun():
return cls_instance.request()
And I want to test the function fun
by patch as showed below:
test_file.py
from core.service.file import fun
class TestCase(unittest.TestCase):
@patch("core.service.file.cls_instance")
def setUp(self, mock):
self.mock = mock.return_value
def test_fun(self):
self.mock.request.return_value = 1
resp=fun()
self.assertEqual(resp, 1)
Test Failed with the message:
Expected : None
Actual : 1
What am I doing wrong here?
Share Improve this question edited Mar 27 at 10:55 User051209 2,5683 gold badges12 silver badges30 bronze badges asked Mar 23 at 12:59 rharrhar 112 bronze badges1 Answer
Reset to default 0You have to use the @patch( )
in the test_fun()
method and not the setUp()
method. So your test file becomes:
import unittest
from unittest.mock import patch
from core.service.file import fun
class MyTestCase(unittest.TestCase):
# ---REMOVE THE setUp() METHOD ---
#@patch("core.service.file.cls_instance")
#def setUp(self, mock):
# self.mock = mock.return_value
@patch("core.service.file.cls_instance")
def test_fun(self, mock):
mock.request.return_value = 1
resp = fun()
self.assertEqual(resp, 1)
if __name__ == '__main__':
unittest.main()
As you can see in my test code I have removed the method setUp()
.
In this way your test passes:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK