chapter seven

7 Substituting dependencies in tests

 

This chapter covers

  • Testing code that relies on the current time
  • Testing code that uses Streams
  • Easier ways to write large strings
  • Using mocks to replace dependencies

Depending on the kind of project you’re working on, it may feel like 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 will 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 will help make testing easier.

The units in the previous chapter have simple relationships. For more complex code, a unit may depend on several other units. This 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 with "stubs" 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, as shown in 7.1.

7.1.1 Using the ISystemTimer

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 Easier ways to write large strings

7.4 Using mocks to replace dependencies

7.4.1 Repository design pattern example

7.4.2 Setting up the unit test class

7.4.3 Validating mocked method calls

7.4.4 Throwing exceptions from mocks

7.5 Summary