Andrew's Digital Garden

Mocks vs Stubs vs Fakes

Stubs deal with state verification, mocks deal with behaviour interaction.

Stubs have predetermined behaviour used for testing - set methods with set responses, further away from the test. Stubs are more reusable, arguably the work put in to create them is saved later when using them. Stub: setup -> exercise -> verify state -> teardown

Mocks are setup with expectations, and are usually closer to the test. This means they don't have predetermined behaviour. Mocks can be considered a type of stub, that register calls they recieve and then you can check if your test called them correctly. Mock: setup data -> setup expectations -> exercise -> verify expectations (verify correct methods have been involved) -> verify state -> teardown

Both help you assert on what happened, but only mocks deal with how its happened.

Fakes is also a term sometimes used in this area. Fakes have working implementations, but their implementation differs to production. Usually a simplified version or something that takes a shortcut, such as using a hashmap for data, rather than a DB. Fakes have a closer to real-world implementation than a stub however - stubs contain hard-coded responses to expected requests, fakes just take a small shortcut over the production implementation.

There are also spies, which monitor the behaviour of something without changing the result.

That being said, depending on who you ask, you may get a different answer.

[[concepts]] [[mocking]] [[testing]]

Mocks vs Stubs vs Fakes