Mocking

Mocking is a technique in Automated Software Testing, primarily used in Unit-Tests.

When the system under test has some dependency which we don’t want to execute in the test, we can replace the dependency with a mock, also known as a test double.

Mocking can be difficult for code that is not testable, especially for code that doesn’t follow inversion of control.

1 Reasons to use a mock instead of the real dependency

1.1 Performance

Maybe the external dependency is slow. Since the dependency is not the actual SUT, executing it for every time these tests are executed can be a waste of time and computing power. That would loose the benefit of a faster feedback loop.

1.2 Dependency Instability

Some external dependencies can be very instable, especially when they are reached via network, or when they’re real-world sensors for example. Using a mock makes it possible to fake their behavior for the SUT, which can make the test stable.

1.3 Ease of testing

Dependencies might throw errors under specific circumstances. These cases can sometimes be hard to force, especially when the error is an OS error. When using a mocked dependency, these errors are easy to throw and therefore the handling of the errors is much easier to test.

Of course this applies to more than just errors.

1.4 Decoupling

While the SUT might require a dependency to exist, it shouldn’t require a specific implementation. Mocking is a great way to force this pattern, as mocking is (near) impossible without it.

2 Backlinks   backlinks