如何为同一个func模拟不同的函数?

h9a6wy2h  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(337)

下面是我要测试的代码

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

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

在编写单元测试时。我想
模拟第一个os.path.exist返回flase,以便不执行func1
模拟第二个os.path.exist返回true,以便执行func2
但是我没有找到一种方法来模拟相同func os.path.exist的不同返回
一种方法是将其 Package 成不同的func和mock。但我不想因为unittest而这样做。有什么好主意吗?

yjghlzjz

yjghlzjz1#

您可以将patch()方法用于 side_effect .
每当调用mock时要调用的函数。请参见“副作用”属性。用于引发异常或动态更改返回值。
例如 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

相关问题