Java Reference
In-Depth Information
public static void main(String[] args) {
CalculatorTest test = new CalculatorTest();
try {
test.testAdd();
}
catch (Throwable e) {
test.nbErrors++;
e.printStackTrace();
}
if (test.nbErrors > 0) {
throw new IllegalStateException("There were " + test.nbErrors
+ " error(s)");
}
}
}
Working from listing 1.3, at B we move the test into its own testAdd method. It's now
easier to focus on what the test does. We can also add more methods with more unit
tests later, without making the main method harder to maintain. At C , we change the
main method to print a stack trace when an error occurs and then, if there are any
errors, end by throwing a summary exception.
Now that you've seen a simple application and its tests, you can see that even this
small class and its tests can benefit from the bit of scaffolding code we've created to
run and manage test results. As an application gets more complicated and tests more
involved, continuing to build and maintain our own custom testing framework
becomes a burden.
Next, we take a step back and look at the general case for a unit testing framework.
C
1.3
Understanding unit testing frameworks
Unit testing frameworks should follow several best practices. These seemingly minor
improvements in the CalculatorTest program highlight three rules that (in our
experience) all unit testing frameworks should follow:
Each unit test should run independently of all other unit tests.
The framework should detect and report errors test by test.
It should be easy to define which unit tests will run.
The “slightly better” test program comes close to following these rules but still falls
short. For example, in order for each unit test to be truly independent, each should
run in a different class instance and ideally in a different class loader instance.
We can now add new unit tests by adding a new method and then adding a cor-
responding try/catch block to main . This is a step up, but it's still short of what
we'd want in a real unit test suite. Our experience tells us that large try/catch
blocks cause maintenance problems. We could easily leave out a unit test and never
know it!
It would be nice if we could add new test methods and continue working. But
how would the program know which methods to run? Well, we could have a simple
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search