The default XCTest file template comes with boilerplate code that we find ourselves deleting most of the time. Instead we have created a clean template that contains just a test case and an empty test that instantiates a system under test object.

On Xcode, after selecting:

File -> New File -> Unit Test Case Class

you will be able to specify in the dialog box just the name of the class you want e.g. Demo, and you'll automatically get a file named DemoTest with a test class name DemoTest and a setup test referencing:

let sut = Demo().

xctest_animated.gif

Changing the Unit Test File Template

Please keep in mind that you might need to change the permissions of these files. To do so, you can right-click on them, and press Get Info, scroll down to Sharing & Permissions and add your user with a Read & Write privilege.

You can replace the contents of Xcode’s Unit Test File template which is located at:

~/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File Templates/Source/Unit Test Case Class.xctemplate/XCTestCaseSwift/FILEBASENAME.swift

with the following:

//___FILEHEADER___

import XCTest

class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_testSubclass___ {

    func test() {
        let sut = ___VARIABLE_productName___()
    }

}

This change does the following two things:

  • It creates the test class name based on the name you provided in the New Unit Test File dialog.
  • It generates a new empty test with an instance of the class you want. To achieve that we use the productName variable which gets the value of the text field Class in the dialog Xcode prompted us.

Naming the Test File

To name the file properly (meaning suffixing with Test automatically) you can edit the template .plist which is located at:

~/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File Templates/Source/TemplateInfo.plist

You can add a suffix when creating a new unit test file, just by appending Test after ___FILEBASENAME___. You will not have to type Test anymore on the dialog, just provide the name of the class you'd like to test.

…
<key>MainTemplateFiles</key>
<dict>
    <key>Objective-C</key>
    <string>___FILEBASENAME___.m</string>
    <key>Swift</key>
    <string>___FILEBASENAME___Test.swift</string>
</dict>