How to stub Python methods without Mock

前端 未结 2 1957
广开言路
广开言路 2021-02-04 09:38

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

2条回答
  •  温柔的废话
    2021-02-04 10:11

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

提交回复
热议问题