如何验证实例对象是否使用一组参数调用其方法?

时间:2019-06-04 16:17:09

标签: python mocking

我有一个正在测试的模块级别的功能。它创建并初始化一个文件变量,我需要断言是否使用正确的参数集对文件进行写操作。如何在文件上调用write()测试。在这种情况下,我必须在这里模拟什么以及如何模拟?

# inside myfolder/mymodule.py
def myfunction():
   file = open("path/to/file", "a+")
   file.write("sample text")

#I need to make sure that file.write() is called with the string "sample text" in my test.
#Using mock.

1 个答案:

答案 0 :(得分:0)

您可以模拟写操作:

def myfunction(file):
   file.write("sample text")

在模拟中(仅作为一个简单示例):

class MockedFile():
    def __init__():
        self.was_called = 0
    def write():
        self.was_called += 1
    def assert():
        assert self.was_called > 0

mocked_file = MockedFile()
myfunction(mocked_file)
mocked_file.assert()