[英]how mock only one method called within the object you are testing
I want to test a method but mock out other methods that it calls. 我想测试一个方法,但模拟出它调用的其他方法。 I created this simple example that should illustrate the concept:
我创建了这个简单的例子来说明这个概念:
class myClass():
def one_method(self):
print "hey"
def two_deep(self):
self.one_method()
def three_deep(self):
self.two_deep()
I was using a python mock framework called Mox and wrote the following code to do this: 我正在使用一个名为Mox的python模拟框架,并编写了以下代码来做到这一点:
def test_partial(self):
self_mox = mox.Mox()
some_object = myClass()
## 1. make your mock
my_mock = mox.MockObject(some_object)
my_mock.one_method().AndReturn('some_value')
self_mox.ReplayAll()
ret = my_mock.three_deep() ## *** SEE NOTE BELOW called "comment":
self_mox.VerifyAll()
Comment: 评论:
I thought that if I called this mock on a method that hadn't been overwritten, then the mock would default to the original code, then I could get the chain of calls that I want, with the last call being replaced... but it doesn't do this. 我以为,如果我在尚未被覆盖的方法上调用此模拟,那么该模拟将默认为原始代码,那么我可以获得所需的调用链,而最后一个调用被替换了……但是它不会这样做。 I can't figure out how to embed a mock object inside a test object that doesn't have an inserting method.
我不知道如何将模拟对象嵌入没有插入方法的测试对象中。
I looked into Partial Mocks and Chained Mocks to solve this, but I couldn't find a way to pull this off. 我研究了Partial Mocks和Chained Mocks来解决这个问题,但是我找不到办法。
Thanks for any help :) 谢谢你的帮助 :)
-- Peter -彼得
Check documentation for StubOutWithMock: https://code.google.com/p/pymox/wiki/MoxDocumentation#Stub_Out https://code.google.com/p/pymox/wiki/MoxRecipes#Mock_a_method_in_the_class_under_test. 检查StubOutWithMock的文档: https : //code.google.com/p/pymox/wiki/MoxDocumentation#Stub_Out https://code.google.com/p/pymox/wiki/MoxRecipes#Mock_a_method_in_the_class_under_test。
So what you needed is: 因此,您需要的是:
def test_partial(self):
self_mox = mox.Mox()
# Create the class as is, instead of doing mock.
some_object = myClass()
# Stub your particular method using the StubOutWithMock.
m.StubOutWithMock(some_object, "one_method")
some_object.one_method().AndReturn('some_value')
self_mox.ReplayAll()
ret = some_object.three_deep()
self_mox.UnsetStubs()
self_mox.VerifyAll()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.