1. Functions and Testing
In this chapter your goal is to become familiar with functions, and writing unit tests to test your functions. This is the most important chapter of the book.
Functions
A function in a programming language is similar to a function in mathematics, but there are important differences.
When you declare a function in Java, you specify its input and
output. The following defines a function sum that takes
two double values a and b as input and
returns a double:
double sum(double a, double b)
{
return a+b;
}However, Java functions are more general, in that a function is not required to have any input variables, nor is it required to have an output value.
void hello()
{
System.out.println("Hello, world!");
}Unit testing
Unit tests are low-level tests of a single function (the target function). In the unit test function, you are given sample input and the expected output (return value). The unit test function runs the target function with the given input and checks that the return value matches what was expected.
Unit test functions are important for verifying the behavior of your code. As you add more code to your project, it is easy to introduce new bugs. Running the unit tests after any changes will give you confidence that your functions still behave as you expect.
Unit tests are also important for ongoing maintenance of your code. For example, if you find a new bug, you can:
- write a new unit test that fails due to the bug
- fix the bug
- verify that all unit tests pass
In the software development world, this strategy of writing tests first is called test driven development (TDD).