Testing on different devices
Table of contents
Run test on different devices
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import Foundation
import XCTest
public extension XCUIApplication {
/// Check if application is running on simulator
public var isRunningOnSimulator: Bool {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}
public var isRunningOnRealDevice: Bool {
return !isRunningOnSimulator
}
public var isRunningOnTablet: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
public var isRunningOnPhone: Bool {
return UIDevice.current.userInterfaceIdiom == .phone
}
}
1
2
3
4
5
6
7
8
// File: TestCaseExtensions > DeviceTypeProtocol.swift
protocol TestOnAnyDevice {}
protocol TestOnPhone {}
protocol TestOnTablet {}
protocol TestOnRealDevice {}
protocol TestOnSimulator {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// File: TestCaseExtensions > BaseTestCase.swift
import XCTest
class BaseTestCase: XCTestCase {
// Check if tests are compatible with the current device
override func perform(_ run: XCTestRun) {
let test = run.test
let testOnPhone = test is TestOnPhone
let testOnRealDevice = test is TestOnRealDevice
let testOnSimulator = test is TestOnSimulator
let testOnTablet = test is TestOnTablet
if (testOnRealDevice && app.isRunningOnSimulator) || (testOnSimulator && app.isRunningOnRealDevice) {
return reasonTestWasSkipped(test.name, message: "Not supported for the current hardware type")
}
if (testOnPhone && app.isRunningOnTablet) || (testOnTablet && app.isRunningOnPhone) {
return reasonTestWasSkipped(test.name, message: "Not supported for the current device type")
}
super.perform(run)
}
private func reasonTestWasSkipped(_ testName: String, message: String) {
let messageForSkipedTest = """
-------- Test Skipped --------
\(testName) [\(message)]
------------------------------
"""
return print(messageForSkipedTest)
}
}
1
2
3
4
5
6
7
8
9
10
11
// File: UITest > ExampleTest.swift
import XCTest
class ExampleTest: BaseTestCase, TestOnPhone {
func testWaitForElement() {
...
}
}
1
2
3
4
5
6
7
8
9
10
11
// File: UITest > ExampleTestTablet.swift
import XCTest
class ExampleTestTwo: BaseTestCase, TestOnTablet, TestOnSimulator {
func testWaitForElement() {
...
}
}