Mocking Static Method Protocols

I ran into an issue on my project where I wanted to add unit tests for my AnalyticsService facade class, which hooks up to Firebase Analytics behind the scenes. The issue is that the Firebase class uses only static method calls for interaction: Analytics.log(“event_name”)

I created an AnalyticsBackEnd protocol that declared a static method and added an extension to the Analytics class to conform to it:

[gist https://gist.github.com/JoshuaSullivan/ec730a453f0a1c24642cbd014229aee5 file=”AnalyticsBackEndProtocol.swift”]

The sticking point was the initializer for the AnalyticsService class: how do I say that I want to receive a class conforming to AnalyticsBackEnd without passing an instance of the class? The solution ended up looking like this:

[gist https://gist.github.com/JoshuaSullivan/ec730a453f0a1c24642cbd014229aee5 file=”AnalyticsService.swift”]

In this way, the AnalyticsService uses the Analytics by default, but allows me to initialize it with the MockAnalyticsBackEnd class for unit testing purposes:

[gist https://gist.github.com/JoshuaSullivan/ec730a453f0a1c24642cbd014229aee5 file=”AnalyticsUnitTest.swift”]