The other answers tell when but not really how, so let me add an answer also.
When
Any time you are writing production code that you are going to keep, you should have Unit Testing for it. The most helpful training that I saw on this was the following 2-part video series:
The first five minutes or so are just intro so you can skip to the end of that.
How
I am using Xcode 7 with Swift.
Start a new project and add a Unit Test.
I am calling mine MyProject
. If you open the MyProjectTests group in the Project Navigator, you will see that Xcode has already created a Unit Test file for you called MyProjectTest.swift.
You can delete all the example methods for now and add a new func
to test your own class method. Be sure to add the line @testable import MyProject
at the top. If your project name has spaces in it then replace the spaces with underscores. (For example, "My Example Project" would use @testable import My_Example_Project
.)
I am following the naming pattern of testMethodNameBeingTested_Senario_ExpectedBehavior
. Unit Test names must begin with "test".
I will do something like this:
import XCTest
@testable import MyProject
class MyProjectTests: XCTestCase {
func testSum_TwoNumbers_ReturnsSum() {
// Arrange (set up the needed objects)
let myClass = MyClass()
// Act (run the method you want to test)
let sum = myClass.sum(1, 2)
// Assert (test that the behavior is as expected)
XCTAssertEqual(sum, 3)
}
}
Of course, the build fails because we haven't added the MyClass
class yet.
Add your class.
I am adding a Swift file to MyProject
called MyClass
.
class MyClass {
func sum(a: Int, _ b: Int) -> Int {
return a + b
}
}
Press the test button next to the Test Unit Class or method to run the test again and it should pass.
To see it fail (an important part of Unit Testing) you could do something like return 0
in the sum
method of MyClass
. Then you would see the following when you run test:
You can go back and fix this and then add more Unit Tests. You can also make other Unit Test files for different classes if you like. Just right click the MyProjectTest group in the Project Navigator and choose "New File" Then choose Test Case Class.
Related
Xcode UI Test example