Define API requirements. It is important to define requirements and outcomes for each method or function that you add to your project. For requirements, include input and output ranges, exceptions thrown and the conditions under which they are raised, and the type of values returned (especially if the values are instances of classes). Specifying requirements and making sure that requirements are met in your code help you write robust, secure code.
Write test cases as you write code. As you design and write each method or function, write one or more test cases to ensure that the API’s requirements are met. Remember that it’s harder to write tests for existing code than for code you are writing.
Check boundary conditions. If a parameter for a method must have values in a specific range, your tests should pass values that include the lowest and highest values of the range. For example, if a procedure has an integer parameter that can have values between 0 and 100, inclusive, the test code for that method should pass the values 0, 50, and 100 for the parameter.
Use negative tests. Negative tests ensure that your code responds to error conditions appropriately. Verify that your code behaves correctly when it receives invalid or unexpected input values. Also verify that it returns error codes or raises exceptions when it should. For example, if an integer parameter must have values in the range 0 to 100, inclusive, create test cases that pass the values -1 and 101 to ensure that the procedure raises an exception or returns an error code.
Write comprehensive test cases. Comprehensive tests combine different code modules to implement some of the more complex behavior of your API. Although simple, isolated tests provide value, stacked tests exercise complex behaviors and tend to catch many more problems. These kinds of tests mimic the behavior of your code under more realistic conditions. For example, in addition to adding objects to an array, you could create the array, add several objects to it, remove a few of them using different methods, and then ensure that the set and number of remaining objects are correct.
Cover your bug fixes with test cases. Whenever you fix a bug, write one or more tests cases that verify the fix.
Leave a Reply