4 Interaction testing using mock objects

This chapter covers

  • Defining interaction testing
  • Reasons to use mock objects
  • Injecting and using mocks
  • Functional examples
  • Modular examples
  • Object-oriented examples
  • Dealing with Complicated Interfaces
  • Partial Mocks

In the previous chapter, you solved the problem of testing code that depends on other objects to run correctly. You used stubs to make sure that the code under test received all the inputs it needed so that you could test the unit of work in isolation.

Also, so far, you’ve only written tests that work against the first two of the three types of exit points a unit of work can have: returning a value and changing the state of the system (you can read more about these in chapter 1).

In this chapter, we’ll look at how you test the third type of exit point—a call to a third-party function, module or object. This is important because many times we’ll have code that depends on things we can’t control. Knowing how to check that type of code is an important skill in the world of unit testing. Basically, we’ll try to see how many ways we can find to prove that our unit of work ends up calling a function that we don’t control, and what values were sent as arguments.

4.1            Interaction Testing, Mocks and Stubs

4.2            Depending on a logger

4.3            Standard Style: Introduce Parameter Refactoring

4.4            The Importance of Mock and Stub Differentiation

4.5            Modular Style Mocks

4.5.1                     Example of production code

4.5.2                     Refactoring the production code in a modular injection style

4.5.3   A test example with modular style injection

4.6            Mocks in a Functional Style

4.6.1   Working with a currying Style

4.6.2   Working with higher order functions and not currying

4.7            Mocks in an Object-Oriented Style

4.7.1   Refactoring Production Code for Injection

4.7.2   Refactoring Production with Interface Injection

4.8            Dealing with complicated interfaces

4.8.1   Example of a Complicated Interface

4.8.2   Writing tests with complicated interfaces