下面的函数打开并加载Json文件。我的问题是什么是测试它的最好方法?如何进行单元测试打开json文件的功能?
def read_file_data(filename, path):
os.chdir(path)
with open(filename, encoding="utf8") as data_file:
json_data = json.load(data_file)
return json_data
filename
和path
形式传入sys.argv中的。
我想,我需要的样本数据在我的测试案例的开始,但不知道我怎么会真正使用它来测试该函数
class TestMyFunctions(unittest.TestCase):
def test_read_file_data(self):
sample_json = {
'name' : 'John',
'shares' : 100,
'price' : 1230.23
}
任何指针将不胜感激。
'self.assertEqual(sample_json,read_file_data(文件名,路径))'的所有代码 – DeepSpace
第一只使该标准Python库的API调用。该代码已经过测试,不应再次测试,只应测试自己的代码。其次,函数涉及使用代码外部的资源(文件):在单元测试中,您通常会嘲笑这些资源。 This [article](https://www.toptal.com/python/an-introduction-to-mocking-in-python)可能会给你一些想法 –