The Risks of Mocking Third-Party Code

Test doubles are great for providing fake versions of your APIs. Not only do they allow you to test your callers in isolation, they also provide design feedback on your API.

When you try to fake out someone else’s API, you miss out on the design benefits of using test doubles. Moreover, you incur extra risks when you mock an interface that you don’t own. Specifically, you can end up with tests that fail when they shouldn’t, or worse, pass when they shouldn’t.

An example will make these risks clearer. The following TwitterUserFormatter class creates a simple string describing a user of the service. Callers will obtain a Twitter::User instance from the Twitter gem (for example, by searching) and pass it to ...

Get Effective Testing with RSpec 3 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.