When to use mock() and proxy()

This is about Python Mocker features. In order to pass in a mock as a parameter to the SUT (subject under test) you might think of creating the mock using either, "mock()" method or "proxy(SomeClass)" method. They both yield mocks but they work differently.

  • mock() should be used for stubs and to mock out functions which are not contained in any class but in mofules.
  • proxy(SomeClass) should be used to mock out classes. Mocker checks that the expectation set on the mock matches an existent method in the class we're proxying. This adds value to the test as it enforces API matching, which is very valuable in Python.
    1.  
    2. def test_whatever():
    3. mockMyClass = self.mocker.proxy(MyClass)
    4. mockMyClass.someMethod()
    5. self.mocker.count(1)
    6. self.mocker.replay()
    7.  
    8. mySutInstance = MySut(mockMyClass)
    9. result = mySutInstance.methodUnderTest()
    10. self.assertTrue(result)
    11. self.mocker.verify()
    12.  

    In the code above, if "someMethod" wasn't existent in MyClass, that would raise an exception. Using mock(), the test would run with same outcome but no exception, so it misses part of the point.

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.