【问题标题】:How to mock differnent for same func?如何为相同的功能模拟不同的?
【发布时间】:2021-07-09 12:29:42
【问题描述】:

这是我要测试的代码

if os.path.exist(path_one):
    func1()

elif os.path.exist(path_two):
    func2()

在编写单元测试时。我想要

  1. 模拟第一个 os.path.exist return Flase 所以 func1 不执行
  2. 模拟第二个 os.path.exist 返回 True 以便 func2 执行

但我没有找到一种方法来模拟相同 func os.path.exist 的不同返回

一种方法是将其包装成不同的 func 和 mock。但我不想仅仅因为单元测试就这样做。有什么好主意吗?

【问题讨论】:

  • 使用队列并让你的模拟出列你想要返回的值。
  • @JohnH 天才,谢谢

标签: python unit-testing mocking


【解决方案1】:

您可以将patch() 方法与side_effect 一起使用。

每当调用 Mock 时要调用的函数。请参阅 side_effect 属性。对于引发异常或动态更改返回值很有用。

例如

main.py:

import os


def func1():
    print('func1')


def func2():
    print('func2')


def main():
    path_one = 'path_one'
    path_two = 'path_two'

    if os.path.exists(path_one):
        func1()

    elif os.path.exists(path_two):
        func2()

test_main.py:

from main import main
from unittest import TestCase, mock
import unittest


class TestMain(TestCase):
    @mock.patch('main.os.path.exists')
    def test_main(self, mock_exists):
        def side_effect(path):
            if(path == 'path_one'):
                return False
            if(path == 'path_two'):
                return True

        mock_exists.side_effect = side_effect
        main()


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

测试结果:

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

OK

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 2010-10-29
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多