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):
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() .
source share