7 Substituting dependencies in tests

 

This chapter covers

  • Handling time in tests
  • Testing with Streams
  • Adding large multiline strings to code
  • Faking dependencies

Depending on the kind of project you’re working on, you may feel that you spend more time writing tests than code. As the code you test gets more complex in terms of relationships and dependencies on other code, the tests also become more complex. Code built on a SOLID foundation (pun intended) can take advantage of certain techniques and libraries to help make tests easier to write. This chapter contains a set of commonly used techniques that help make testing easier.

The units in chapter 6 have simple relationships. For more complex code, a unit may depend on several other units, which is true of many ASP.NET Core components. ASP.NET Core has built-in dependency injection and implements the dependency inversion principle. In testing situations, dependencies can be replaced by mocks or fakes that are designed to do nothing except return specific values if needed.

7.1 Testing code that relies on the current time

Consider the implementation of a stopwatch, shown in the following listing.

7.2 Testing code that uses Streams

7.2.1 Memory stream

7.2.2 File stream from copied files

7.2.3 Manifest resource streams

7.3 Finding easier ways to write large strings

7.4 Replacing dependencies with fakes

7.4.1 Considering an example repository design pattern

7.4.2 Setting up the unit-test class

7.4.3 Validating faked method calls

7.4.4 Verifying the number and order of calls

7.4.5 Throwing exceptions from fakes

Summary