问题描述
谁能告诉我为什么这不起作用?
Can anyone tell me why this isn't working?
也许有人可以提出更好的方法?
Perhaps someone could suggest a better way?
推荐答案
有几个问题.
首先,您使用 mock.patch
的方式不太正确.当用作装饰器时,它仅在装饰函数内将给定的函数/类(在本例中为 datetime.date.today
)替换为 Mock
对象.所以,只有在你的 today()
中,datetime.date.today
才会是一个不同的函数,这似乎不是你想要的.
First of all, the way you're using mock.patch
isn't quite right. When used as a decorator, it replaces the given function/class (in this case, datetime.date.today
) with a Mock
object only within the decorated function. So, only within your today()
will datetime.date.today
be a different function, which doesn't appear to be what you want.
你真正想要的似乎更像是这样的:
What you really want seems to be more like this:
很遗憾,这行不通:
这会失败,因为 Python 内置类型是不可变的 - 请参阅 这个答案了解更多详情.
This fails because Python built-in types are immutable - see this answer for more details.
在这种情况下,我将自己继承 datetime.date 并创建正确的函数:
In this case, I would subclass datetime.date myself and create the right function:
现在你可以这样做了:
这篇关于试图模拟 datetime.date.today(),但不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!