Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python library for creating stubs/fake objects

I am looking for python stubbing library. Something that could be used to create fake classes/methods in my unit tests.. Is there a simple way to achieve it in python..

Thanks

PS: I am not looking for mocking library where you would record and replay expectation.

Difference between mock and stubs

like image 451
StackUnderflow Avatar asked Jun 24 '26 21:06

StackUnderflow


1 Answers

We do this.

class FakeSomethingOrOther( object ):
   def __init__( self ):
       self._count_me= 0
   def method_required_by_test( self ):
       return self.special_answer_required_by_test
   def count_this_method( self, *args, *kw ):
       self._count_me += 1

It doesn't take much to set them up

class TestSomething( unittest.TestCase ):
    def setUp( self ):
        self.requiredSomething = FakeSomethingOrOther()
        self.requiredSomething.attribute_required_by_test= 12
        self.requiredSomething.special_answer_required_by_test = 32
        self.to_be_tested = ActualThing( self.requiredSomething )

Since you don't require complex statically checked type declarations, all you need is a class with the right methods. You can force test attribute values in trivially.

These things are really, really easy to write. You don't need a lot of support or libraries.

In other languages (i.e., Java) it's very hard to write something that will pass muster with static compile-time checking. Since Python doesn't have this problem, it's trivial to write mocks or fake implementations for testing purposes.

like image 167
S.Lott Avatar answered Jun 27 '26 12:06

S.Lott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!