Mocking Functions and Traits

Learn how to use Mockito to mock functions and traits in Scala.

Mocking interfaces

In this lesson, we’re going to see how to mock functions defined in a Scala trait. In OOP we’re often encouraged to define interfaces to declare nonimplemented methods and properties and then delegate the actual implementation to abstract or concrete classes implementing these interfaces. This practice leverages polymorphism, one of the core concepts of OOP.

It’s always preferable to depend on interfaces rather than on their concrete implementations. As we’ll see, mocking interfaces is usually much simpler than mocking a concrete class. Furthermore, depending on (and consequently mocking) interfaces helps us respect the Liskov substitution principle: objects of a superclass should be replaceable with objects of its subclasses without breaking the application.

In practice, we often define interfaces only when we have to mock them in our tests. Otherwise, we might end up with many interfaces implemented by a single class. While this is surely cleaner from an architectural point of view, it leads to a complicated interface with tons of redundant code.

Creating mocks for a trait

We’ve already experimented with behavioral verification by writing our own CourseDouble that contains logic to track the invocations of some methods. However, by importing Mockito, we get that for free.

As a first step, we’ll rewrite our Fixture trait to use mocks generated by Mockito.

Get hands-on with 1200+ tech skills courses.