Skip to content

Instantly share code, notes, and snippets.

@blaix
Created March 30, 2012 23:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blaix/2257854 to your computer and use it in GitHub Desktop.
Save blaix/2257854 to your computer and use it in GitHub Desktop.
Mocking new instance of class and verifying the arguments in python with flexmock
# Mock new instances of a class (verify that it's initialized with specific arguments)
# First argument to __new__ is the class, so pass `object` because we don't care about that part
flexmock(MyClass).should_receive('__new__').once.with_args(object, 'arg1', 'arg2').and_return(fake_object)
MyClass('wrong', 'arguments') # => MethodSignatureError
MyClass('arg1', 'arg2') # => <fake_object>
# Stub new instances of a class (simply replace any new instance with another object)
flexmock(MyClass).new_instances(fake_object)
MyClass('wrong', 'arguments') # => <fake_object>
MyClass('arg1', 'arg2') # => <fake_object>
@juliomistral
Copy link

Just ran into this little buzz saw...

Remember to use should_call if you just want to spy on the constructor, but still pass the call onto the actual implementation.

The following just returns None:

flexmock(MyClass).should_receive('__new__').once.with_args(object, 'arg1', 'arg2') 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment