I am just getting into unit testing in Xcode, so I decided to play a bit with the default test target that gets created with any of Xcode's project templates.
As a start, I decided to perform a very basic test to see whether the AppDelegate
instance's window
property (of type UIWindow?
) is actually set.
This is my test code:
import UIKit
import XCTest
import Sample // This is the App target (app is called "Sample")
class SampleTests: XCTestCase
{
override func setUp(){
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown(){
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample(){
// This is an example of a functional test case.
if let delegate = UIApplication.sharedApplication().delegate{
if let myDelegate = delegate as? AppDelegate {
if let window = myDelegate.window {
XCTAssert(true, "Pass")
}
else{
XCTFail("App Delegate Has No Window")
}
}
else{
XCTFail("Application Delegate Object Is of The Wrong Type")
}
}
else{
XCTFail("Application Delegate Not Present")
}
}
}
At first, I couldn't build the test target because the AppDelegate class was not accessible. I tried two approaches, with different results:
If I mark both my
AppDelegate
class and all its properties/methods as public, the test builds with no errors and succeeds (i.e.,window
optional is notnil
).If, instead, I mark class, properties and methods of AppDelegate as
internal
, but modify the source file's target membership to also belong to the test target (not just the app target), the test builds with no errors but fails ("Application Delegate Object Is of The Wrong Type", i.e., the conditional cast toAppDelegate
type fails).
Looks as though with the second approach, a different application delegate is present at runtime. Does anybody know what is happening?