![](/img/trans.png)
[英]How to mock global variable in a imported module in python unit test?
[英]How to write unit test for code that depends on imported module
拥有以下内容的文件
import something
if something:
# do some things here
else:
raise Exception
我怎么能写单元测试,涵盖else
上述文件的分支?
因此,您希望在测试中“取消导入”模块。 您可以通过以下方式删除命名空间中
del something
没错,它不会进入else块。 然后你可以用try-except块重写主模块,如下所示。
try:
if something:
print "Yes"
except NameError:
print "Something not imported"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.