Don't mock

what you don't own
(How to write good tests)

TDD reminder

TDD is just as much about design as it is about testing

An external API can and will change its signature and behaviour

On external dependencies, you never have control over them

When mocking an external API the test doesn't drive the design

Type of external dependencies

- HTTP APIs / Network

- Global state

- DB

- Third party libraries

- File system

- etc.

Scenario I

Class A

3rd Party

V1

Unit Test for
Class A

Mocked 3rd Party

Code

Test

Build

Scenario I

Class A

3rd Party

V2

Unit Test for
Class A

Mocked 3rd Party

Code

Test

V2 With a change in behavior​

Build

Scenario II

Class A

3rd Party

V1

Unit Test for
Class A

Mocked 3rd Party

Code

Test

Class B

3rd Party

V1

Unit Test for
Class B

Mocked 3rd Party

Build

Build

Scenario II

Class A

3rd Party

V3

Unit Test for
Class A

Mocked 3rd Party

Code

Test

Class B

3rd Party

V3

Unit Test for
Class B

Mocked 3rd Party

V3 With a change in the interface​

Build

Build

Disadvantages of breaking this rule

- The code will become coupled to external dependencies

- Leaky abstractions

- The code will be poorly isolated from external dependecies

- External dependencies migh pollute an entire codebase

- Bad design

- Testing becomes hard

Solution

Class A

3rd Party

Unit Test for
Class A

Mocked Adapter

Code

Tests

Adapter

IT Test For Adapter

When 3rd Party changes

Class A

3rd Party

Unit Test for
Class A

Mocked Adapter

Code

Tests

Adapter

IT Test For Adapter

Good practices

- Isolate your software from external dependencies

- Avoid external dependencies polluting your entire codebase

- If the dependency changes, only one class/test should change

- Create good interfaces that make sense in your domain

- Create abstractions on top of your dependencies

- Encapsulate complexity and reduce coupling

- Test your adapter using the third party library directly if possible

- Avoid leaky abstractions

Useful resources

QA?

Made with Slides.com