"

Writing Useful Tests

Now that we’ve thoroughly discussed why we want tests, let’s look at how to write effective tests.

An effective test

  • tests something specific, such as a specific method or specific behavior
  • is named so as to clearly indicate what’s being tested
    • test methods often start with test, like testMenuPrintEmptyList or testMenuPrint or testMenuPrintInvalidPrintData
  • gives you a clear idea of what the bug could be based solely on what test failed
    • if testGetName fails, you can pretty much bet the bug is in getName. If testInstanceVariables fails, you don’t really have any useful information as to what part of your code is breaking.
  • is independent of other tests
    • as a general rule of thumb, and true for the tests you’ll write in this class

Why is independence important? Suppose you use the same object for all of your tests. In one of the first tests, an instance variable gets set to the wrong value. This incorrect value causes that test and all subsequent tests to fail. The subsequent tests may be false failures; if the instance variable had been set correctly, they would have passed.

To ensure independence, set up each test from scratch. If you’re testing a class, create a new object for each test and configure that object as needed. You can use other set up methods to create objects, but do not use the same object for each test. You should not assume that your tests will be run in any particular order. Obviously, if you wrote your own test suite, your program will run in the order you implemented. However, if you use a testing framework (which is highly recommended), your tests are not guaranteed to be run in any specific order.

License

Icon for the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License

Computer Science II Copyright © by Various is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, except where otherwise noted.