Skip to content

Mocking

Mocking

In order to write efficient unit tests, we need to remove the external dependencies from your application code. We can do this by replacing it with an implementation we control or a mock.

A mock is a general term for a "pretend" object that we use in place of a real one with credentials and an external address. We can specify expected responses and attributes to put our application logic through a variety of scenarios without generating real network traffic.

Dependency Injection

Dependency Injection is a technique used to separate dependencies from the business logic in our code. Rather than introduce a dependency between two classes, we can wrap REST APIs or system calls which allows us to "inject" our own implementation at will.

This can quickly go overboard as it can potentially make the code more complex to work with. Rather use this intentionally and make it a goal to develop a maintainable system.

Mocks vs. Fakes

While Mocks are objects that a developer constructs themselves for the purpose of testing, there is a similar concept called Fakes which actually have working implementations. An example of this would be an in-memory database standing in for a external instance which would allow you test code locally. Although similar in concept, the distinction between Fakes and Mocks are important. Read more here.

Helpful Resources

  • https://microsoft.github.io/code-with-engineering-playbook/automated-testing/unit-testing/#why-unit-testing
  • https://microsoft.github.io/code-with-engineering-playbook/automated-testing/unit-testing/mocking/