首页 > 解决方案 > 如何为相同的功能模拟不同的?

问题描述

这是我要测试的代码

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

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

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

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

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

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

标签: pythonunit-testingmocking

解决方案


您可以将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

推荐阅读