我不熟悉Python中的单元测试,在运行测试时遇到了一些问题。我想实现如下测试类,如下所示:https://www.toptal.com/python/an-introduction-to-mocking-in-python,但是稍微
被改进的。
我想用pathlib.Path.is_file
代替os.path.isfile
。在
这是要测试的实际类:
import os
from pathlib import Path
class FileUtils:
@staticmethod
def isFile(file):
return Path(file).is_file()
@staticmethod
def deleteFile(file):
if FileUtils.isFile(file):
os.remove(file)
这是测试课:
^{pr2}$这将导致以下错误消息:
Finding files... done.
Importing test modules ... done.
======================================================================
FAIL: testDeleteFile (FileUtilsTest.FileUtilsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "...\AppData\Local\Continuum\anaconda3\lib\site-packages\mock\mock.py", line 1305, in patched
return func(*args, **keywargs)
File "...\FileUtilsTest.py", line 13, in testDeleteFile
self.assertFalse(osMock.remove.called, 'Failed to not remove the file if not present.')
AssertionError: True is not false : Failed to not remove the file if not present.
----------------------------------------------------------------------
Ran 1 test in 0.003s
FAILED (failures=1)
如何通过使用@mock.patch
修饰符测试方法FileUtils.deleteFile
?在
这里的问题是,当您修补模块中的符号
Path
时,您正在替换Path
的构造函数的符号。但是is_file
不是构造函数的属性-它是构造函数返回的对象的属性。将调用构造函数,并对返回值调用is_file
。所以你也要嘲笑这一部分。为此,请设置一个mock,以便在调用Path
符号时返回。在相关问题 更多 >
编程相关推荐