Catching memory leaks using Unit Tests in Xcode

Catching memory leaks using Unit Tests in Xcode

Having a codebase backed up by unit tests provides peace of mind for the contributors and the business, allowing for a fast and safe continuous development.

Ideally, when testing an object dealing with asynchronous code, unit tests check for memory leaks, since this issue is more difficult to catch and debug otherwise.

Let’s take as an example a simple data loader.

No alt text provided for this image

Usually, there’s a System Under Test for each isolated test file, created in a dedicated helper method. More about this approach in the article 7 important aspects when writing Unit Tests in Xcode.

The test file would look something like this.

No alt text provided for this image

Memory leaks can happen sometimes, but not always, making it preferable to check for them in all unit tests to increase the chances of catching them early in the development process.

Here is how to track for memory leaks of any given instance in unit tests.

No alt text provided for this image

The instance should not outlive the test method, meaning once the tear-down method is executed, the instance should be nil. This method works with AnyObject as to make it more reusable.

I have put the method in an XCTestCase extension since it shouldn’t be tied to a specific test file. Generic test helpers can be extracted and shared by multiple test files across a module or project.

With the current code, when it happens to have a memory leak, Xcode will provide a stack trace for the failing tests, but the highlighted error is pointing at the trackForMemoryLeaks method. This is correct, but not ideal, since extra steps are required to identify which test method has failed and what steps led to a memory leak.

But there’s a solution to this. By simply passing the file and line down to the lower-level methods that make assertions, Xcode will point directly at the failing test, where the test method name and steps should make it easy to understand what’s not working and when.

No alt text provided for this image

This is a clean way to track memory leaks in unit tests and it can be used with almost every SUT in any project.

To view or add a comment, sign in

More articles by Robert Tanase

Insights from the community

Others also viewed

Explore topics