views:

57

answers:

2

I'm a C# dev moving into some Python stuff, so I don't know what I'm doing just yet. I've read that you don't really need Dependency Injection with Python. I've been told you can instantiate objects in your code and have them run the way you want, however, you can point methods on those objects to my own stubs defined in my tests - supposedly without mocks.

Is this true? I've tried to do it and can't quite get it working. How is this actually done? How do I stub a method in Python without a mocking library?

+1  A: 

If I understand correctly your are talking about Monkey Patching. If this is the case, check this thread.

This blog post should also be useful.

I hope this helps.

Thanks, Damian

Damian Schenkelman
Thanks for the posts and threads. This is exactly what I was looking for and great examples for how to do it right.
Corey Coogan
+1  A: 

Here's a basic example. Note that the production getData() method is never called. It has been mocked out with a stub.

import unittest
class ClassIWantToTest(object):

    def getData(self):
        print "PRODUCTION getData called"
        return "Production code that gets data from server or data file"

    def getDataLength(self):
        return len(self.getData())

class TestClassIWantToTest(unittest.TestCase):

    def testGetDataLength(self):
        def mockGetData(self):
            print "MOCK getData called"
            return "1234"

        origGetData = ClassIWantToTest.getData
        try:
            ClassIWantToTest.getData = mockGetData
            myObj = ClassIWantToTest()
            self.assertEqual(4, myObj.getDataLength())
        finally:
            ClassIWantToTest.getData = origGetData

if __name__ == "__main__":
    unittest.main()
Peter Lyons
Thanks Peter. This is what I'm looking for.
Corey Coogan