Design considerations and trade-offs

Test cases are required to be deliverable when creating software. Any feature that is without an automated test might as well not exist. A feature certainly can't be trusted to be correct if there's no test. If it can't be trusted, it shouldn't be used.

The only real trade-off question is whether to use doctest or unittest or both. For simple programming, doctest may be perfectly suitable. For more complex situations, unittest will be necessary. For frameworks where the API documentation needs to include examples, a combination works well.

In some cases, simply creating a module full of TestCase class definitions may be sufficient. The TestLoader class and test discovery features may be perfectly adequate to locate all of the tests.

More generally, unittest involves using TestLoader to extract multiple test methods from each TestCase subclass. We package the test methods into a single class based on who they can share class-level setUp(), and possibly setUpClass(), methods with.

We can also create TestCase instances without TestLoader. In this case, the default method of runTest() is defined to have the test case assertions. We can create a suite from instances of this kind of class.

The most difficult part can be designing for testability. Removing dependencies so that units can be tested independently can sometimes feel like adding to the software design's complexity. In most cases, the time expended exposing dependencies is time invested in creating more maintainable and more flexible software.

The general rule is this: an implicit dependency between classes is bad design.

A testable design has explicit dependencies; these can easily be replaced with mock objects. The pytest framework provides the monkeypatch fixture. This permits us to write tests that isolate the unit being tested by patching the dependencies. While this is handy, it's often simpler and more reliable to provide for simple, visible dependency injection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset