Mocking Classes

Learn some best practices for mocking classes.

Dependencies among different units should be modeled using traits as much as possible since it allows for a cleaner design and simplified unit testing. It’s generally better to mock a trait rather than a concrete class. However, there are situations where we might need to mock a concrete class. For example, this can happen a lot when dealing with legacy code that we can’t refactor.

Creating mocks for classes

If the class we want to mock is not declared final, the creation of the mocks looks exactly like what we did for traits.

Get hands-on with 1200+ tech skills courses.