Class Mocks

Understand how to effectively mock the interfaces and behaviors of a class.

Why do we mock classes?

There are three main reasons to mock classes. The first is the separation of concerns. If the code we are testing depends on a class, we don’t want this dependency to cause the passing or failing of our test. Mocking allows us to ensure the class is behaving as expected and that only the actual code at hand is being tested.

The second is our testing environment. Classes might interact with a database or make calls to external services. One way to handle this is through class mocks.

Last, gaining deeper insights into how our classes are calling methods can be very useful in testing our code. Mocking classes allows us to make assertions on how methods are called, what arguments they have, the number of times they are called, and other parameters.

How do we mock a class?

We have four options for mocking our classes. The option we choose depends on our ...