Mocking Objects

Learn some best practices to make the code using objects more testable.

Mocking Scala objects

In this lesson, we’re going to turn our attention to another big topic: mocking the Scala object, also called a singleton object when defined at the top level. Mocking objects is a fairly complex topic; it requires a bit of discussion about how to design your code to have testable objects. You can’t inject an object into a parameter the same way you inject the instance of a class.

object Test:
  val a = 5

class Unit():
  val b = Test.a
class Test():
  val a = 5

class Unit(t: Test):
  val b = t.a

From the example above, it’s clear that invoking object functions directly is a highway to writing untestable (or almost untestable) code. While we can easily create a mock for a trait or class and pass the mocked instance as a parameter to the unit under test, we can’t do the same thing with an object.

Singleton objects in Scala

As their name suggests, singleton objects implement the singleton pattern. Whenever we write object Obj, we’re declaring a class with only a single instance. In Scala when a singleton object has the same name as a class, it’s called a companion object. Companion objects are a powerful feature because these companions (class and object) can access each other’s private members. That is, the instance of a class can ...