最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to patch global class in python correctly - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 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
发布评论

评论列表(0)

  1. 暂无评论