Testing in Combine: Collecting Values

Eduardo Sanches Bocato
2 min readDec 11, 2020

A generic approach to collect values when testing values in combine.

Introduction

When testing something in Combine it's very common to end up having to collect values in order to validate scenarios like a state change, for example.
We could simply subscribe (i.e call sink) to a publisher inside the test and validate that, but it's possible to avoid all that boilerplate code with a simple implementation.

If you are new to Combine, here are some good references to give you a good start:

Case Study Scenario

For our examples, let's assume the code below. Which is a very simple ViewModel from a MVVM approach with state modeling and a service that returns us a list of Strings.

A simple ViewModel from an MVVM approach.

Tests: The Common Case

Normally, we subscribe to the value we want to observe, collect the values that need to be validated and and check them later.

A common case for the tests.

This is the most common approach, but there will be always some repetitive code to collect the states, subscribe, keep the cancellables and so on…

The Collector Approach

Implementation

Collector implementation.

Usage

Collector usage examples.

Tests Example

Testing with a Collector.

Conclusion

In the end, both approaches are valid, but with a Collector we can focus mainly the test code instead, avoiding some boilerplate, which leads to a test suite with better readability and easier to maintain.

--

--

Eduardo Sanches Bocato

iOS Engineer, AI enthusiast, Crossfit/Gymnastics. Currently working as iOS Lead @adidas