Step 1: Prepare the Mock

The challenge we face with testing Dave’s reconnection logic is we have no way to control what that connector returns when called in the playTrack method.

 def​ playTrack(track)
 if​ !@connector.is_connected
  @connector.connect
 end
 
 return​ @connector.handle_request(track)
 end

The way the code is currently written, the @connector is going to try to connect to the real music service every time it’s called, and what we want to do is replace the real @connector object with a fake one—or a mock.

The most common way to set up test code to be mocked is to inject the objects you want to mock, in through the constructor of the object under test. This is known as dependency injection.[14]

The way dependency injection ...

Get The Way of the Web Tester now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.