1

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?

1 Answer 1

0

You 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
Sign up to request clarification or add additional context in comments.

5 Comments

Why do you say that the first argument to assertEqual is the expected value? They're documented as just first and second.
When I use PyCharm Community to execute a test and it fails the error message calls Expected the first argument and Actual the second argument. It is the same with JUnit (Java Framework); I didn't read this part the documentation; Thank you I'm going to read it now.
@user2357112 You are right in the documentation are indicated as first and second arguments I'm going to edit my answer and remove the paragraph.
@User051209 Can you please tell why patching in setup won't work? Isn't setUp run before each test?
In general the patch decorator is used for the test method and not for the setUp method. Now I can't retest your code. Is important for you put patch before setUp()? I have never done this on my test! If my code works could be an acceptable answer for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.