iOS:使用Swift中的void func进行单元测试
问题描述:
我想测试此方法,它不返回值,但我想检查是否正常工作。 你能给我一些建议吗?iOS:使用Swift中的void func进行单元测试
func login() {
if Utility.feature.isAvailable(myFeat) {
if self.helper.ifAlreadyRed() {
self.showWebViewController()
} else {
let firstVC = FirstViewController()
self.setRootController(firstVC)
}
} else {
let secondVC = SecondViewController()
self.setRootController(secondVC)
}
}
那么在这里应用单元测试的最佳方法是什么?
答
测试副作用是一种方法。但是对于像上述代码那样的例子,我更喜欢一种子类和期望的方法。
您的代码有三条不同的路径。
- 如果功能可用且已经显示红色,则显示Web视图控制器。
- 如果功能可用且不是红色,请显示第一个视图控制器。
- 如果功能不可用,请显示第二个视图控制器。
所以假设这login()
功能是遵循此格式FooViewController
,一种可能性是编写测试部分:
func testLoginFeatureAvailableAndNotAlreadyRed() {
class TestVC: FooViewController {
let setRootExpectation: XCTExpectation
init(expectation: XCTExpectation) {
setRootExpectation = expectation
super.init()
}
override func setRootController(vc: UIViewController) {
defer { setRootExpectation.fulfill() }
XCTAssertTrue(vc is FirstViewController)
// TODO: Any other assertions on vc as appropriate
// Note the lack of calling super here.
// Calling super would inaccurately conflate our code coverage reports
// We're not actually asserting anything within the
// super implementation works as intended in this test
}
override func showWebViewController() {
XCTFail("Followed wrong path.")
}
}
let expectation = expectationWithDescription("Login present VC")
let testVC = TestVC(expectation: expectation)
testVC.loadView()
testVC.viewDidLoad()
// TODO: Set the state of testVC to whatever it should be
// to expect the path we set our mock class to expect
testVC.login()
waitForExpectationsWithTimeout(0, handler: nil)
}
您测试通过检查其副作用无效的功能。单元测试应验证呼叫前的状态,拨打电话,确保没有异常,然后检查呼叫后的状态。 – dasblinkenlight
你能给我写一个例子吗,因为它在开始时并不是我的灵魂 – CrazyDev