Outline

This is from a tweet which you can find here.

If you're not familiar with the various types of "mocks" used in unit testing. Here's a quick and dirty rundown.

The academic term is not "mock" it's actually "test double".

There are 5 types of generally accepted test doubles:

  1. Dummies
  2. Fakes
  3. Stubs
  4. Spies
  5. Mocks (yes, basically mocks are a type of mock, lol)

Most people just use the word "mock" to refer to any of the 5 types of test doubles, but sometimes, you may need to refer to the specific mock type of test double. Also, the API for most libraries will include a Mock class or something with the word mock in the name...those will be Mocks, not a general type of test double.

1. Dummies

Dummies are just an object passed around but not used. Mostly used to fill a parameter slot.

2. Fakes

This is a working object but with a short-circuited implementation that won't work in a production environment. The classic example is an in-memory database instead of a real database. It's important to understand that Fakes have an actual implementation. But a non-production-worthy one.

3. Stubs

This is an object that looks like the real object it's doubling as, but provides canned answers to calls made during the test. For example, it returns 5 when you call add() no matter what numbers you pass.

4. Spies

Again, they look like the real object, but they record what methods were called and in what order and with what parameters. Used to make sure that the test did or did not call something correctly.

MOST mocking libraries provide an object that is a mix of stub and spy, and most unit tests just use that, and rarely use the other types.

5. Mocks

Mocks are a test double that is pre-programmed to expect certain calls to happen, and returns specific answers when those calls happen. They fail when the expected order/calls don't happen the specific way.

Mocks are generally considered the hardest type of test double to use. Many people prefer stubs/spies over mocks (myself included).

It's also worth noting that Mocks violate the AAA setup of unit tests, so they almost read backward from what you expect in a test.

Discounted Courses

Here at Thinkster, we use educational science to teach you five times faster than you would learn the same topics elsewhere. By joining as a Pro subscriber you have access to our complete library on courses on Angular, React, Vue, JavaScript, and More.

To help you get started, use this link for a discount on a monthly membership.

Or save even more with an annual membership.

 

I finished! On to the next chapter