Writing better test cases

We have already seen that the best test cases test a small unit of code at a time. They also need to be fast. A programmer needs to run tests at least once before every commit to the source control. Even a delay of a few seconds can tempt a programmer to skip running tests (which is not a good thing).

Here are some qualities of a good test case (which is a subjective term, of course) in the form of an easy-to-remember mnemonic fast, independent, repeatable, small, transparent (FIRST) class test case:

  • Fast: The faster the tests, the more often they are run. Ideally, your tests should complete in a few seconds.
  • Independent: Each test case must be independent of others and can be run in any order.
  • Repeatable: The results must be the same every time a test is run. Ideally, all random and varying factors must be controlled or set to known values before a test is run.
  • Small: Test cases must be as short as possible for speed and ease of understanding.
  • Transparent: Avoid tricky implementations or ambiguous test cases.

Additionally, ensure that your tests are automatic. Eliminate any manual steps, no matter how small. Automated tests are more likely to be part of your team's workflow and easier to use for tooling purposes.

Perhaps, even more important are the don'ts to remember while writing test cases:

  • Do not (re)test the framework: Django is well tested. Don't check for URL lookup, template rendering, and other framework-related functionalities.
  • Do not test implementation details: Test the interface and leave the minor implementation details. It makes it easier to refactor this later without breaking the tests.
  • Test models most, templates least: Templates should have the least business logic, and they change more often.
  • Avoid HTML output validation: Test views use their context variable's output rather than its HTML-rendered output.
  • Avoid using the web test client in unit tests: Web test clients invoke several components and are, therefore, better suited for integration tests.
  • Avoid interacting with external systems: Mock them if possible. Database is an exception since the test database is in-memory and quite fast.

Of course, you can (and should) break the rules where you have a good reason to (just like I did in my first example). Ultimately, the more creative you are at writing tests, the earlier you can catch bugs and the better your application will be.

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

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