Mocks or Stubs?

I have a method that calls two other methods in it.

def main_method(self, query): result = self.method_one(query) count = self.method_two(result) return count def method_one(self, query): #Do some stuff based on results. #This method hits the database. return result def method_two(self, result): #Do some stuff based on result. #This method also hits the database. return count 

I am not very good at unit testing and have never worked with Mocks and Stubs.

I am not sure how to create a unit test for my first method. Since method_one and method_two get into the database many times, and they are very expensive, I decided to use mox to create a layout or stub to eliminate the need to get into the database.

I would really appreciate it if someone who had experience with Mocks and Stubs gave me some tips on using mocks and stubs for my business.

Thanks for the advanced.

+4
source share
1 answer

Before worrying about testing main_method() , check out the smaller methods first. Consider method_one() . For discussion purposes, suppose it exists in this class:

 class Foo(object): def method_one(self, query): # Big nasty query that hits the database really hard!! return query.all() 

To test this method without getting into the database, we need an object that knows how to respond to the all() method. For instance:

 class MockQuery(object): def all(self): return [1,2] 

Now we can check this:

 f = Foo() q = MockQuery() assert f.method_one(q) == [1,2] 

This is a basic illustration. The real world is often more complicated. To keep abreast of writing a test, your all() layout is likely to do something more interesting than returning a constant. Similarly, if method_one() contains a bunch of different logic, our MockQuery may need to be more complex, that is, able to adequately respond to more methods. Often, when trying to check the code, you realize that your original design was overloaded: you may need to reorganize method_one() into smaller, more rigidly defined and, therefore, more tested parts.

Using the same logic in the hierarchy, you can create a MockFoo class that knows how to simplify the path to method_one() and method_two() .

+5
source

All Articles