Swift Test Tutorial: How To Keep Tests Short (10 lines or less)

In this lesson

It’s very important to keep your tests short. In this lesson, I’ll show you how I do this and why it’s so important.


Tap on time to skip ahead


In this lesson, I’m going to talk about how to keep your tests short in terms of lines of code. I’m talking about functions, like this one. A good rule of thumb is that each test should be a maximum of 10 lines of code.


I’m going to scroll down slowly through my tests, and you’ll notice that I have quite a few. There are none that are more than ten lines of code. If you look at lines like this, these are just wrapped lines. If I wasn’t recording this at a lower screen resolution, these likely would be on one line. Most of my tests, really, are about three lines of code each. At least in this test case.


Integration tests are a little more complicated typically. If we scroll down here we can still see that all of these tests are within 10 lines of code. Even with the try/catch for testing code that throws exceptions. How do we do that?


Well, let’s take a look at a couple of things. First of all, move as much code as you can into the setup phase of the test. Here, I don’t do a whole lot other than creating an instance of the component or the subsystem that I’m testing. But, you’ll notice that by doing that, I don’t have to put that one line in every single one of my tests. Moving that to the setup phase allows me to reduce the number of lines in each test, since that line is necessary for every single test that I write.


Another thing that can be done to keep your tests short is to extract duplicated code, or similar code, into helper functions. Here in this test, you’ll notice that I call a helper function to create tables. I happen to do the same thing here and here and everywhere that I need something similar. If we look at this helper function, this is quite a few lines of code that I was able to move out of each test and just call it from the test. One thing I could consider doing to even remove that is to move this call to the setup phase. There may be a little bit of extra work necessary to do that but it might be valuable because it allows me to reduce my tests by another line- here I have a blank line- reducing that even further.


The last thing I can do is just keep my tests focused on one thing. Here is a particular test case, there’s quite a bit going on here. I’m testing that I’m executing a query and it should throw an exception. What I do is I call my helper function and then I go into a try/catch block. I execute a query and it should throw an exception. If I get to this line, I’m going to fail the test, but down here in the catch clause, I’m making an assertion that my cursor is nil because the test should throw an exception and I should not get a cursor back. Being focused on one thing, like this, allows me to keep my tests very concise.