如何编写Firestore的单元测试

时间:2019-08-16 08:40:50

标签: swift unit-testing google-cloud-firestore

我是初学者,需要在下面测试我的FirestoreService类。我尝试进行模拟,但是没有进入快照。我只需要测试失败的情况。

class FirebaseService {

    let decoder = JSONDecoder()
    var movies = [Movies]()

    enum Result {
        case success([Movies])
        case failure(Error)
    }

    func getMovies(completion: @escaping (Result) -> Void) {

       let movieReference = Firestore.firestore().collection("movies").order(by: "id")

        movieReference.addSnapshotListener { (snapshot, _) in
            guard let snapshot = snapshot else {return}
            do {
                self.movies = try snapshot.decoded()
                completion(.success(self.movies))
            } catch {
                completion(.failure(error))
            }
        }
    }
  • 这是我的FirebaseServiceTests类
XCTestclass FirebaseServiceTests: XCTestCase {

    func testGetMovies() {
        let firebaseSercice = FirebaseService()
        let expectation = XCTestExpectation(description: "Wait for queue change ")
       firebaseSercice.getMovies { result in
        XCTAssertNotNil(result)
        expectation.fulfill()
        }
        wait(for: [expectation], timeout: 0.5)
    }

    func testGetMoviesWithMock() {
    let firebaseSercice = MockDatabaseReference()
    let expectation = XCTestExpectation(description: "Wait for queue change ")
    firebaseSercice.getMovies { result in
        XCTAssertNil(result)
        expectation.fulfill()
        }
    wait(for: [expectation], timeout: 0.5)
    }
}
private class MockDatabaseReference: FirebaseService {
    override func getMovies(completion: @escaping (Result) -> Void) {

    let movieTestReference =  Firestore.firestore().collection("mov").order(by: "id")
    movieTestReference.addSnapshotListener { (snapshot, _) in
    guard let snapshot = snapshot else {return}
    do {
    self.movies = try snapshot.decoded()
    completion(.success(self.movies))
    } catch {
    completion(.failure(error))
    }
    }
  }
}

你能解释一下怎么做吗?谢谢。

0 个答案:

没有答案