简体   繁体   中英

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:

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.

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM