HomeToolsAbout

Mock vs Stub

Mock vs Stub

Stub

Provides pre-defined responses to method calls and is usually used to control the environment of the test. It helps you verify if the system behaves correctly based on the return values it produces.

  • Doesn't care about how many times or in what way a method is called. It just returns fixed values.

Mock

Simulates behavior and also allows you to verify interactions with the dependencies.

In addition to providing responses, it records and asserts that certain methods were called with specific arguments.

  • whether certain methods were called, and if they were called with the correct arguments

What is a mock

Mock is about controlling a behavior.

  • We need to mock when you want to control the behavior in a test.

Case for/against mock

source

The argument usually revolves around avoiding excessive coupling between your tests and your code.

If you are asserting things like how a particular interface was called, what arguments it was called with, how many times it was called etc, this is asserting the implementation details, which is almost never (but not never never) desired.

You usually only want to test the end behavior, which is why integration testing is the more useful kind of test.

However, testing a full integration suite is sometimes impractical. You might need to integrate with dozens of systems.

  • You might want to test failure modes that only occur under heavy load. This can be difficult or impossible to trigger inside a dev/qa environment. The easy solution is to mock your dependency and have it return the failure condition that you’ve seen in prod.
  • Sometimes, an integration test is quite literally not possible, because the vendor of your system doesn’t provide any testing client for you to use.
  • Integration tests are also very slow.
AboutContact