2017-06-30 1 views
1

私は、UITableViewを持つアプリケーション用の単体テストケースを、サーバからのデータで書いています。 numberOfRowsInSectionを除き、私のTableViewのテストケースを追加しました。非同期サービス呼び出しのTableViewユニットテスト

私はのUITableViewのテストケースのためのリンクの下に、次のい: Xcode 5 test UITableview with XCTest Framework

誰が非同期サービス呼び出しからのデータを示しているnumberOfRowsInSectionのためのテストケースを作成する方法を提案することができますか? アイデアや例があれば、非常に役に立ちます。

答えて

1

OHHTTPStubsを使用してjsonでデータを偽装することができます。顔データを含むjsonファイルをプロジェクトに追加します(適切なターゲットの選択には注意してください)。

func testNumberOfRowsInSection() { 
    let fetchExpectation = expectation(description: "Test Fetching") 
    let viewController = YourViewController() 
    YourDataManager.shared.fetchData(for: endpoint, success: { 
     XCTAssertEqual(viewController.tableView.numberOfRows(inSection: 0), expectedNumberOfRows, "Number Of Rows In Section 0 Should Match!") 
     fetchExpectation.fulfill() 
    }, failure: nil) 
    waitForExpectations(timeout: 60, handler: nil) 
} 
:あなたが偽のデータにしたくない場合は

import XCTest 
import OHHTTPStubs 

class TestSomeRequest: XCTestCase { 

    // MARK: - Attributes 
    fileprivate let endpoint = "yourendpoint" 
    fileprivate let apiUrl = "yoururl" 
    fileprivate let path = "yourpath" 
} 


// MARK: - Setup & Tear Down 
extension TestSomeRequest { 
    override func setUp() { 
     super.setUp() 
     stub(condition: isHost((URL(string: apiUrl)?.host)!) && isPath(path), response: {_ in 
      guard let path = OHPathForFile("TestDataJson.json", type(of: self)) else { 
       preconditionFailure("Could Not Find Test File!") 
      } 
      return OHHTTPStubsResponse(fileAtPath: path, statusCode: 200, headers: ["Content-Type": "application/json"]) 
     }) 
    } 

    override func tearDown() { 
     super.tearDown() 
     OHHTTPStubs.removeAllStubs() 
    } 
} 


// MARK: - Tests 
extension TestSomeRequest { 
    func testNumberOfRowsInSection() { 
     let fetchExpectation = expectation(description: "Test Fetching") 
     let viewController = YourViewController() 
     YourDataManager.shared.fetchData(for: endpoint, success: { 
      XCTAssertEqual(viewController.tableView.numberOfRows(inSection: 0), expectedNumberOfRows, "Number Of Rows In Section 0 Should Match!") 
      fetchExpectation.fulfill() 
     }, failure: nil) 
     waitForExpectations(timeout: 60, handler: nil) 
    } 
} 

、ちょうどこの試験方法を使用します。そして、データをテストするために、次のコードを使用します

関連する問題