3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Unit test で LifeCycleメソッドを呼ぶ

Posted at

参考:
Testing for viewDidLoad in iOS
[iOS、Swift] ユニットテストの時に、任意のタイミングでViewDidLoad()、ViewWill(Did)Appear()、ViewWill(Did)Disappear()を呼び出す方法 - Qiita

viewDidLoad

実装

class ViewController: UIViewController {
	var searchBar = UISearchBar()
	override func viewDidLoad() {
		searchBar.delegate = self
	}
}

extension VIewController: UISearchBarDelegate {
	public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    //なんかの処理
  }
}

viewDidLoadはクラスが初期化されただけでは呼ばれないため
この場合テストは失敗する。

class ViewControllerTests: XCTestCase {
	func test_set_delegate_to_searchBar() throws {
		let viewController = ViewController()
    
    
    XCTAssertNotNil(viewController.searchBar.delegate)
	}
}

ではテストでviewDidLoadを呼べばいいかというとベストプラクティスではない。
(テストはパスする)

class ViewControllerTests: XCTestCase {
	func test_set_delegate_to_searchBar() throws {
		let viewController = ViewController()
    
		viewController.viewDidLoad()
    
    XCTAssertNotNil(viewController.searchBar.delegate)
	}
}

viewDidLoadはviewにアクセスされた時に実行されるイベントなので、
結果的にviewDidLoadを2回呼んでしまうことになる。
つまりviewにアクセスするだけでいい。

class ViewControllerTests: XCTestCase {
	func test_set_delegate_to_searchBar() throws {
		let viewController = ViewController()
    
		_ = viewController.view
    
    XCTAssertNotNil(viewController.searchBar.delegate)
	}
}

または loadViewOfNeededを呼ぶ

viewController.ViewController()
viewController.loadViewIfNeeded()

ViewWillAppear

beginAppearanceTransitionの第一引数をtrueにして呼ぶ

viewController = ViewController()
viewController.beginAppearanceTransition(true, animated: false)

ViewDidAppear

beginAppearanceTransitionの第一引数をtrueにして呼んだ後に
endAppearanceTransitionを呼ぶ

viewController = ViewController()
viewController.beginAppearanceTransition(true, animated: false)
viewController.endAppearanceTransition()

ViewWillDisappear

beginAppearanceTrasitionの第一引数をfalseにして呼ぶ

viewController = ViewController()
viewController.beginAppearanceTrasition(false, animated: false)

ViewWillDisappear

beginAppearanceTrasitionの第一引数をfalseにして読んだ後に
endAppearanceTrasitionを呼ぶ

viewController = ViewController()
viewController.beginAppearanceTrasition(false, animated: false)
viewController.endAppearanceTrasition()

ViewWillLayoutSubviews

layoutViewIfNeedeを呼ぶ

viewController = ViewController()
viewController.view.layoutViewIfNeeded()
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?