2016-08-18 6 views
5

値を返さないこのメソッドをテストしたいが、うまく動作するかどうかチェックしたい。 私にいくつかの提案を教えてもらえますか?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) 
      } 
    } 

ここで単位テストを適用するにはどうすればよいでしょうか?

+2

あなたはその副作用をチェックすることで、ボイドの機能をテストします。単体テストは、呼び出し前の状態を確認し、呼び出しを行い、例外がないことを確認し、呼び出し後に状態を確認する必要があります。 – dasblinkenlight

+0

あなたは私に例を書いてもいいですか – CrazyDev

答えて

3

試験副作用の1つのアプローチです。しかし、問題のコードのような例の場合、私は実際にサブクラスと期待のアプローチを好む。

コードには3つの異なるパスがあります。

  1. 機能が利用可能で既に赤色である場合、show web view controller。
  2. 機能が利用可能で、まだ赤でない場合は、最初のView Controllerを表示します。
  3. 機能が利用できない場合は、2番目のView Controllerを表示します。

だから、一つの可能​​性は、この形式に従ってテストを書いている、この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) 

} 
関連する問題