mock any instance

Phlip phlip2005 at gmail.com
Mon Dec 14 16:31:26 EST 2009


Pythonistas:

One important design principle is "construction encapsulation". That's
where nobody creates anything, they always use things passed to them.

Without this principle, when I need to mock the encapsulated item,
some mock libraries provide an "any instance" facility.

For example, here's a mock on one method of only one object:

   object = Thang()
   object.method = Mock()
   object.method()  #  <--  calls the mock, not the real method

I need to mock the method on any instance spawned by a given class:

   Thang.method = MockAnyInstance()
   object = Thang()
   object.method()  #  <--  calls the mock, not the real method

That will avoid "cutting a hole in the bulkhead" just to get to the
'object = Thang()' line, to let me spoof out the Thang.

Does anyone have any idea how to do that with the good-old Mocker
here?

  http://python-mock.sourceforge.net/

if I should use a different mocker, I would prefer it behave like that
mock, for aesthetic reasons, and also to avoid the need to replace all
our existing Mocks with a new one, following the rule that we should
not use too many classes to do the same thing (DRY).

--
  Phlip
  http://c2.com/cgi/wiki?ZeekLand



More information about the Python-list mailing list