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.
Consider the implementation of a stopwatch, as shown in 7.1.