Chapter 3. Using stubs to break dependencies

 

This chapter covers

  • Defining stubs
  • Refactoring code to use stubs
  • Overcoming encapsulation problems in code
  • Exploring best practices when using stubs

In the previous chapter, you wrote your first unit test using NUnit and explored several testing attributes. You also built tests for simple use cases, where all you had to check on were return values from objects or the state of the unit under test in a bare-bones system.

In this chapter, we’ll take a look at more realistic examples where the object under test relies on another object over which you have no control (or that doesn’t work yet). That object could be a web service, the time of day, threading, or many other things. The important point is that your test can’t control what that dependency returns to your code under test or how it behaves (if you wanted to simulate an exception, for example). That’s when you use stubs.

3.1. Introducing stubs

Flying people into space presents interesting challenges to engineers and astronauts, one of the more difficult being how to make sure the astronaut is ready to go into space and operate all the machinery during orbit. A full integration test for the space shuttle would have required being in space, and that’s obviously not a safe way to test astronauts. That’s why NASA built full simulators that mimicked the surroundings of a space shuttle’s control deck, which removed the external dependency of having to be in outer space.

3.2. Identifying a filesystem dependency in LogAn

3.3. Determining how to easily test LogAnalyzer

3.4. Refactoring your design to be more testable

3.5. Variations on refactoring techniques

3.6. Overcoming the encapsulation problem

3.7. Summary

sitemap