Python: 模拟导入的模块方法

Python: mock imported module method

我必须测试方法 pyautogui.click() 是否被调用。这是我的 Player.py 文件:

# Player.py

import pyautogui

class Player:
    def play():
        pyautogui.click(100, 100)

这是我的测试文件:

# Test_Player.py

import unittest
from Player import Player

class Test_Player(unittest.TestCase):
    def test_play(self):
        player = Player()
        player.play()
        # assert pyautogui.click is called once

我尝试了 pyautogui.click = MagicMock() 和许多其他东西,但我真的找不到如何断言 pyautogui.click() 被调用一次。

您正在文档中查找 unittest.mock.patch. Patch replaces an imported module with a mock version for the duration of a test. The most important thing to understand about it is that you have to patch something where it is imported, not where it lives. That means you patch Player.pyautogui, not pyautogui itself. You should read "Where to Patch"

您可以将补丁装饰器添加到您的测试函数中,并将您想要用模拟替换的内容传递给它。您传递给它的字符串应该是您 运行 进行测试的位置的相对路径(通常是项目的根目录)。我假设您的两个文件都在同一个文件夹中,并且您 运行 从该文件夹进行测试。

补丁装饰器随后会将 MagicMock 的实例作为参数传递给您的测试函数 self。您可以随意命名。我将在下面的示例中将其称为 mock_pyautogui。在您的函数中,您可以像往常一样进行断言。

import unittest
from Player import Player

class Test_Player(unittest.TestCase):

    @unittest.mock.patch("Player.pyautogui")
    def test_play(self, mock_pyautogui):
        player = Player()
        player.play()

        self.assertEqual(1, mock_pyautogui.click.call_count)