简体   繁体   English

Mocking python 测试中 class 中的一个方法

[英]Mocking a method inside class in python test

I am new to Python and writing a unit test for the already existing code.我是 Python 的新手,并为现有代码编写单元测试。

I have the following Python code structure:我有以下 Python 代码结构:

root_project:
-- src 
   -- signUp 
      -- __init__.py 
      -- abc.py 
      -- xyz.py

abc.py contains the following code: abc.py包含以下代码:

from . import xyz
class Abc: 

      def __init__(self):
         pass 
      
      def start_process(self):
         xyz.start_timer()

I want to mock xyz.start_timer() inside method start_process of class Abc so that start_timer() mock version can be used.我想在 class Abc 的方法start_process中模拟xyz.start_timer() ,以便可以使用start_timer()模拟版本。

How can I achieve this?我怎样才能做到这一点?

You just need to patch xyz.start_timer() , I just added return to start_process to show that the patching really does what it should:您只需要修补xyz.start_timer() ,我只是将return添加到start_process以表明修补确实做了它应该做的:

import xyz
import unittest
from unittest import mock


class Abc:
    def __init__(self):
        pass

    def start_process(self):
        return xyz.start_timer()


class Test_Abc(unittest.TestCase):
    @mock.patch('xyz.start_timer', return_value=True)
    def test_start_process(self, start_process):
        a = Abc()
        self.assertTrue(a.start_process())


if __name__ == '__main__':
    unittest.main()

Out:出去:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

You can simply patch the start_timer function using mock.patch() .您可以使用mock.patch()简单地修补start_timer function 。

abc.py abc.py

import xyz

class Abc: 

      def __init__(self):
         pass 
      
      def start_process(self):
         xyz.start_timer()

test_abc.py test_abc.py

from unittest import mock, TestCase

from abc import Abc

class Test_Abc(TestCase):

    @mock.patch("abc.start_timer")
    def test_start_process(self, mock_start_timer):
        # your test code

Notice that I have patched abc.start_timer and not xyz.start_timer .请注意,我已经修补abc.start_timer而不是xyz.start_timer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM