簡體   English   中英

為什么我不能用 unittest.mock.patch 有效地模擬功能?

[英]Why I cannot effectively mock function with unittest.mock.patch?

我正在嘗試為其他函數編寫 UT 函數。 兩者都在同一個模塊中。 看起來unittest.mock.patch()調用通過而沒有錯誤,但沒有模擬任何東西,所以我在示例代碼中遇到了異常。 所以,我的問題是:如何用unittest.mock.patch模擬foo

import unittest
import unittest.mock

def foo():
        raise Exception("not implemented")

def bar():
        foo()

class UT(unittest.TestCase):

        def testBar(self):
                with unittest.mock.patch('mock_test.foo',spec=True) as mock_foo:
                        bar()    # <- original foo is called here

unittest.main()

這是一種使用unittest.mock.patch並修補foo返回值的方法。 請參閱示例中的注釋:

import unittest
from unittest.mock import patch


def foo():
        raise Exception("Not implemented")


def bar():
        return foo()


class UT(unittest.TestCase):

        def testBar(self):
            # foo is mocked to raise a ValueError and catch it during the test
            with patch('__main__.foo', side_effect=ValueError):
                with self.assertRaises(ValueError):
                    bar()

            # foo is mocked to raise and exception and catch it during the test
            with patch('__main__.foo', side_effect=Exception):
                with self.assertRaises(Exception):
                    bar()

            # foo is mocked to return 1
            with patch('__main__.foo', return_value=1):
                self.assertEqual(bar(), 1, "Should be equal to 1")

            # foo is mocked to return an object
            with patch('__main__.foo', return_value={}):
                self.assertIsInstance(bar(), dict, "Should be an instance of dict")


unittest.main()

輸出:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

更多信息請訪問官方文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM