Hello brothers and sisters, Leo here. Today’s topic is how to trigger the UIViewController memory warning on your unit tests in Swift.

We’ll explore some *hacks* to trigger the memory on the UIViewController. Let’s go!

Problem – The UIViewController memory warning

You have to test the code inside the didReceiveMemoryWarning() method from a view controller in your test suite.

This definitely is a tricky problem. First because if you try yourself to cause a memory warning, you’ll probably end in a situation where your unit test isn’t reliable as they should be because you don’t have control over when the system will call the memory warning method, so the runtime of the tests will be unstable.

Fortunately, you have the option to trigger manually by calling this piece of code inside your tests case:


Now in your tests, you can check what should happen when a memory warning is called on your view controllers.

To check that you need to override didReceiveMemoryWarning function. From Apple’s doc:

Your app never calls this method directly. Instead, this method is called when the system determines that the amount of available memory is low.

You can override this method to release any additional memory used by your view controller. If you do, your implementation of this method must call the super implementation at some point.

This way performing from the selector is the right way to test the UIViewContrller.

And we are done!


This is the fallthrough keyword and how to use it, and I hope you enjoy it as I did! Any thoughts or feedbacks are very welcome!

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for the reading and… That’s all folks.

Credits – image