Why Test Your Code

After you debug and optimize your code, you might still need to test it. Debugging lets you catch run-time errors that appear in your code. Testing lets you catch bugs that appear when users provide unexpected combinations of input arguments, or when they run your code on different platforms or MuPAD® versions. It also helps to catch bugs that can appear when you or someone else edits your code later or when you need to integrate parts of the program written by different developers. MuPAD provides tools for unit testing your code. These tools let you write and execute your own test scripts for a particular part of your code, for example, for a function or a procedure.

Suppose you create the procedure that accepts two numeric arguments, a and b, compares them, and returns the larger number:

f := proc(a:Type::Numeric, b:Type::Numeric)
begin
  if a = b or a > b then
    return(a)
  else
    return(b)
  end_if
end_proc:

The type Type::Numeric includes integers, rationals, floating-point numbers, and also complex numbers. Therefore, any complex numbers are valid arguments of the procedure f. The procedure f has a flaw in its design because you cannot compare two complex numbers. If you call this procedure for two different complex numbers, the procedure call results in an error. Nevertheless, the procedure works if you call it for equal complex numbers:

f(I, I)

Suppose you decide to keep the procedure f as it is. It works for equal complex arguments. The error only occurs when the complex arguments are not equal. Later, you or somebody else forgets about the issue with complex numbers, but sees that the procedure can be improved as follows:

f := proc(a:Type::Numeric, b:Type::Numeric)
begin
  if a >= b then
    return(a)
  else
    return(b)
  end_if
end_proc:

This code looks shorter, and takes advantage of the >= operator. However, if some users relied on the procedure f to recognize equal complex numbers, their code breaks when they use the updated version:

f(I, I)
Error: Cannot evaluate to Boolean. [_leequal]
  Evaluating: f

If you do not create and use a test script for the procedure f, you might never realize that the procedure stopped working for the particular choices of arguments. Even if you tested this choice of arguments before, you might forget to test it for the updated version. Writing a test script and running it every time when you (or somebody else) update your code helps to avoid unexpected loss in functionality.

Was this topic helpful?