Unit testing is a fundamental practice in Extreme Programming [Beck 1999], but most nontrivial code is difficult to test in isolation. You need to make sure that you test one feature at a time, and you want to be notified as soon as any problem occurs. Normal unit testing is hard because you are trying to test the code from outside. We propose a technique called Mock Objects in which we replace domain code with dummy implementations that emulate real code. These Mock Objects are passed to the target domain code which they test from inside, hence the term Endo-Testing. This practice is similar to writing code stubs with two interesting differences: we test at a finer level of granularity than is usual, and we use our tests and stubs to drive the development of our production code. Our experience is that developing unit tests with Mock Objects leads to stronger tests and to better structure of both domain and test code. Unit tests written with Mock Objects have a regular format that gives the development team a common vocabulary. We believe that code should be written to make it easy to test, and have found that Mock Objects is a good technique to achieve this. We have also found that refactoring Mock Objects drives down the cost of writing stub code.
Unit testing with Mock Objects An essential aspect of unit testing is to test one feature at time; you need to know exactly what you are testing and where any problems are. Test code should communicate its intent as simply and clearly as possible. This can be difficult if a test has to set up domain state or the
domain code causes side effects. Worse, the domain code might not even expose the features to allow you to set the state necessary for a test. For example, the authors have written tools to extend the development environment in IBM’s VisualAge for Java, one of which generates template classes. This tool should not write a new template class if one already exists in the environment. A naïve unit test for this requirement would create a known class, attempt to generate a template class with the same name, and then check that the known class has not changed. In VisualAge this raises incidental issues such as whether the known class has been set up properly, ensuring that the user has the right permissions, and cleaning up after the test should it fail – none of which are relevant to the test.
|