【发布时间】:2018-11-15 09:32:31
【问题描述】:
我想测试一个包含with 语句的函数的类:
func_to_test():
....
with self.__elastic_generator.get() as es:
print 'about to use the es connection....'
所以我模拟了 elstic_generator,并在创建测试类时模拟了 get 函数:
elastic_gen = mock.Mock()
elstic_gen.get = mock.Mock()
elastic_gen.get.side_effect = ['mocked elastic connection']
tested_class = TestedClass(elastic_gen)
tested_class.func_to_test()
但由于某些原因,使用 with 语句时不起作用。
但是,如果在不使用with 的情况下获得连接,像这样:
x = self.__elastic_generator.get()
然后它工作正常,我得到x = 'mocked elastic connection'。
所以我猜这个问题与使用 with 时进行的更多函数调用有关,并且我没有模拟这些函数。
有人可以解释一下幕后发生了什么,我还应该模拟什么才能使用with 语句对其进行测试?
谢谢。
【问题讨论】:
标签: python python-2.7 mocking with-statement python-mock