Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ccabanero/68cd8ff461316930f707 to your computer and use it in GitHub Desktop.
Save ccabanero/68cd8ff461316930f707 to your computer and use it in GitHub Desktop.
Sample iOS Unit Tests: Working with a ViewController composed of a UILabel
import XCTest
@testable import UnitTests
class ExampleTests: XCTestCase {
var viewControllerUnderTest: ViewController!
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
self.viewControllerUnderTest = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController
self.viewControllerUnderTest.loadView()
self.viewControllerUnderTest.viewDidLoad()
}
override func tearDown() {
super.tearDown()
}
func testViewControllerIsComposedOfLabel() {
XCTAssertNotNil(self.viewControllerUnderTest.label, "ViewController under test is not composed of a UILabel")
}
func testViewControllerInitializesLabelText() {
XCTAssert(self.viewControllerUnderTest.label.text == "Vader", "ViewController under test does not initialize the text property of UILabel correctly")
}
func testLabelAfterButtonTap() {
let button: UIButton = UIButton()
viewControllerUnderTest.handleTap(button)
let expectedLabelText = "Hello testing"
let actualLabelText = viewControllerUnderTest.label.text
XCTAssertEqual(expectedLabelText, actualLabelText, "Label text of: \(expectedLabelText) not equal to text: \(actualLabelText)")
}
}
@kobeumut
Copy link

kobeumut commented Mar 9, 2021

Hello Dear,
You did good work on unit testing. It's appreciatable and helpful material.
I just tried your code also but still facing a problem.
Xcode report an error with description which is "Could not cast value of type 'UnitTetsingDemo.ViewController' (0x105b871d8) to 'UnitTetsingDemoTests.ViewController' (0x1201929b0)".
Please help me how I resolve this issue.
Thanks in advance :)

@sAurangzaib, I have same issue. Did you solve this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment