如何测试模拟方法调用的默认参数?

yshpjwxd  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(287)

main.py

def sendContent(path = config.path):
    contentData = content.extractData(path)
    jsonContent = json.dumps(contentData, ensure_ascii=False, indent=4, sort_keys=True)
    logging.info("Creating json...")
    return config.createContent(jsonContent)

我想测试这个方法调用的属性。为此,我不得不模仿这个方法。但是,我可能不知道该怎么做,因为如果我不在mock中指定属性,它就不会使用默认参数(config.path)。
以下是我的(众多)测试之一:
tests/testmain.py

def testSendContent():
    main.sendContent = Mock()
    main.sendContent()
    main.sendContent.assert_called_with(config.path)

assertionerror:未找到预期的调用
如果在第3行,我放置main.sendcontent(config.path),那么测试当然可以。。。但如果我不放任何东西,mock就不会使用默认参数。
谢谢你的帮助

lxkprmvk

lxkprmvk1#

“testsendcontent”第二行上的模拟方法调用main.sendcontent()不是sendcontent函数的真正调用,它只是一个替换模拟函数调用。因为它是在没有参数的情况下调用的,而不是像您预期的那样使用实函数的默认参数。
因此,您可以只使用模拟调用fit,而不是使用名为的assert_检查它:
如果您想在测试过程中绕过sendcontent的函数调用,可以继续模拟它,并指定预期的返回值,如下所示:main.sendcontent=mock(return\u value=“some\u path\u here”)
或者,如果只想测试sendcontent,不要使用mock。只需调用它并使用:self.assertequal(sendcontent(),“some_path”)

相关问题