How to use verify method of ExpectationGroup class

Best Mockingbird code snippet using ExpectationGroup.verify

OrderedVerification.swift

Source:OrderedVerification.swift Github

copy

Full Screen

...7import Foundation8import XCTest9/// Enforce the relative order of invocations.10///11/// Calls to `verify` within the scope of an `inOrder` verification block are checked relative to12/// each other.13///14///     // Verify that `canFly` was called before `fly`15///     inOrder {16///       verify(bird.canFly).wasCalled()17///       verify(bird.fly()).wasCalled()18///     }19///20/// Pass options to `inOrder` verification blocks for stricter checks with additional invariants.21///22///     inOrder(with: .noInvocationsAfter) {23///       verify(bird.canFly).wasCalled()24///       verify(bird.fly()).wasCalled()25///     }26///27/// An `inOrder` block is resolved greedily, such that each verification must happen from the oldest28/// remaining unsatisfied invocations.29///30///     // Given these unsatisfied invocations31///     bird.canFly32///     bird.canFly33///     bird.fly()34///35///     // Greedy strategy _must_ start from the first `canFly`36///     inOrder {37///       verify(bird.canFly).wasCalled(twice)38///       verify(bird.fly()).wasCalled()39///     }40///41///     // Non-greedy strategy can start from the second `canFly`42///     inOrder {43///       verify(bird.canFly).wasCalled()44///       verify(bird.fly()).wasCalled()45///     }46///47/// - Parameters:48///   - options: Options to use when verifying invocations.49///   - block: A block containing ordered verification calls.50public func inOrder(with options: OrderedVerificationOptions = [],51                    file: StaticString = #file, line: UInt = #line,52                    _ block: () -> Void) {53  createOrderedContext(at: SourceLocation(file, line), options: options, block: block)54}55/// Additional options to increase the strictness of `inOrder` verification blocks.56public struct OrderedVerificationOptions: OptionSet {57  public let rawValue: Int58  public init(rawValue: Int) {59    self.rawValue = rawValue60  }61  62  /// Check that there are no recorded invocations before those explicitly verified in the block.63  ///64  /// Use this option to disallow invocations prior to those satisfying the first verification.65  ///66  ///     bird.name67  ///     bird.canFly68  ///     bird.fly()69  ///70  ///     // Passes _without_ the option71  ///     inOrder {72  ///       verify(bird.canFly).wasCalled()73  ///       verify(bird.fly()).wasCalled()74  ///     }75  ///76  ///     // Fails with the option77  ///     inOrder(with: .noInvocationsBefore) {78  ///       verify(bird.canFly).wasCalled()79  ///       verify(bird.fly()).wasCalled()80  ///     }81  public static let noInvocationsBefore = OrderedVerificationOptions(rawValue: 1 << 0)82  83  /// Check that there are no recorded invocations after those explicitly verified in the block.84  ///85  /// Use this option to disallow subsequent invocations to those satisfying the last verification.86  ///87  ///     bird.name88  ///     bird.canFly89  ///     bird.fly()90  ///91  ///     // Passes _without_ the option92  ///     inOrder {93  ///       verify(bird.name).wasCalled()94  ///       verify(bird.canFly).wasCalled()95  ///     }96  ///97  ///     // Fails with the option98  ///     inOrder(with: .noInvocationsAfter) {99  ///       verify(bird.name).wasCalled()100  ///       verify(bird.canFly).wasCalled()101  ///     }102  public static let noInvocationsAfter = OrderedVerificationOptions(rawValue: 1 << 1)103  104  /// Check that there are no recorded invocations between those explicitly verified in the block.105  ///106  /// Use this option to disallow non-consecutive invocations to each verification.107  ///108  ///     bird.name109  ///     bird.canFly110  ///     bird.fly()111  ///112  ///     // Passes _without_ the option113  ///     inOrder {114  ///       verify(bird.name).wasCalled()115  ///       verify(bird.fly()).wasCalled()116  ///     }117  ///118  ///     // Fails with the option119  ///     inOrder(with: .onlyConsecutiveInvocations) {120  ///       verify(bird.name).wasCalled()121  ///       verify(bird.fly()).wasCalled()122  ///     }123  public static let onlyConsecutiveInvocations = OrderedVerificationOptions(rawValue: 1 << 2)124}125private func getAllInvocations(in contexts: [UUID: MockingContext],126                               after baseInvocation: Invocation?) -> [Invocation] {127  return contexts.values128    .flatMap({ $0.allInvocations.value })129    .filter({130      guard let baseInvocation = baseInvocation else { return true }131      return $0.uid > baseInvocation.uid132    })133    .sorted(by: { $0.uid < $1.uid })134}135private func assertNoInvocationsBefore(_ capturedExpectation: CapturedExpectation,136                                       baseInvocation: Invocation?,137                                       contexts: [UUID: MockingContext]) throws {138  let allInvocations = getAllInvocations(in: contexts, after: baseInvocation)139  140  // Failure if the first invocation in all contexts doesn't match the first expectation.141  if let firstInvocation = allInvocations.first,142     !firstInvocation.isEqual(to: capturedExpectation.invocation) {143    let endIndex = allInvocations.firstIndex(where: {144      $0.isEqual(to: capturedExpectation.invocation)145    }) ?? allInvocations.endIndex146    let unexpectedInvocations = Array(allInvocations[allInvocations.startIndex..<endIndex])147    148    let failure = TestFailure.unexpectedInvocations(149      baseInvocation: capturedExpectation.invocation,150      unexpectedInvocations: unexpectedInvocations,151      priorToBase: true152    )153    throw ExpectationGroup.Failure(error: failure,154                                   sourceLocation: capturedExpectation.expectation.sourceLocation)155  }156}157private func assertNoInvocationsAfter(_ capturedExpectation: CapturedExpectation,158                                      baseInvocation: Invocation?,159                                      contexts: [UUID: MockingContext]) throws {160  let allInvocations = getAllInvocations(in: contexts, after: baseInvocation)161  guard !allInvocations.isEmpty else { return }162  163  let failure = TestFailure.unexpectedInvocations(164    baseInvocation: capturedExpectation.invocation,165    unexpectedInvocations: allInvocations,166    priorToBase: false167  )168  throw ExpectationGroup.Failure(error: failure,169                                 sourceLocation: capturedExpectation.expectation.sourceLocation)170}171private struct Solution {172  let firstInvocation: Invocation?173  let lastInvocation: Invocation?174  175  enum Failure: Error {176    case unsatisfiable177  }178}179private func satisfy(_ capturedExpectations: [CapturedExpectation],180                     at index: Int = 0,181                     baseInvocation: Invocation? = nil,182                     contexts: [UUID: MockingContext],183                     options: OrderedVerificationOptions) throws -> Solution {184  let capturedExpectation = capturedExpectations[index]185  let allInvocations = findInvocations(in: capturedExpectation.mockingContext,186                                       with: capturedExpectation.invocation.selectorName,187                                       before: nil,188                                       after: baseInvocation)189  var nextInvocationIndex = 1190  191  while true {192    if options.contains(.onlyConsecutiveInvocations), baseInvocation != nil {193      try assertNoInvocationsBefore(capturedExpectation,194                                    baseInvocation: baseInvocation,195                                    contexts: contexts)196    }197    do {198      // Try to satisfy the current expectations.199      let allInvocations = try expect(capturedExpectation.mockingContext,200                                      handled: capturedExpectation.invocation,201                                      using: capturedExpectation.expectation,202                                      before: allInvocations.get(nextInvocationIndex),203                                      after: baseInvocation)204      guard index+1 < capturedExpectations.count else { // Found a solution!205        return Solution(firstInvocation: allInvocations.first, lastInvocation: allInvocations.last)206      }207      208      // Potential match with the current base invocation, try satisfying the next expectation.209      let allMatchingInvocations = allInvocations.filter({ $0.isEqual(to: capturedExpectation.invocation) })210      let result = try satisfy(capturedExpectations,211                               at: index+1,212                               baseInvocation: allMatchingInvocations.first,213                               contexts: contexts,214                               options: options)215      216      // Check if still satisfiable when using the next invocation as a constraint.217      if let nextBaseInvocation = result.firstInvocation {218        try expect(capturedExpectation.mockingContext,219                   handled: capturedExpectation.invocation,220                   using: capturedExpectation.expectation,221                   before: nextBaseInvocation,222                   after: baseInvocation)223      }224      225      return Solution(firstInvocation: allInvocations.first, lastInvocation: result.lastInvocation)226    } catch let error as ExpectationGroup.Failure { // Propagate the precondition failure.227      throw error228    } catch { // Unable to satisfy the current expectation.229      guard nextInvocationIndex+1 <= allInvocations.count else {230        throw Solution.Failure.unsatisfiable // Unable to grow the window further.231      }232      nextInvocationIndex += 1 // Grow the invocation window.233    }234  }235}236/// Internal helper for `inOrder` verification scopes.237///   1. Creates an attributed `DispatchQueue` scope which collects all verifications.238///   2. Checks invocations on each mock using the provided `options`.239func createOrderedContext(at sourceLocation: SourceLocation,240                          options: OrderedVerificationOptions,241                          block scope: () -> Void) {242  let group = ExpectationGroup { group in243    let contexts = group.expectations.reduce(into: [UUID: MockingContext]()) {244      (result, expectation) in245      result[expectation.mockingContext.identifier] = expectation.mockingContext246    }247    248    // Check for invocations prior to the first expectation's invocation(s).249    if options.contains(.noInvocationsBefore), let firstExpectation = group.expectations.first {250      try assertNoInvocationsBefore(firstExpectation, baseInvocation: nil, contexts: contexts)251    }252    253    do {254      let result = try satisfy(group.expectations, contexts: contexts, options: options)255      256      // Check for invocations after the last expectation's invocation(s).257      if options.contains(.noInvocationsAfter), let lastExpectation = group.expectations.last {258        try assertNoInvocationsAfter(lastExpectation,259                                     baseInvocation: result.lastInvocation,260                                     contexts: contexts)261      }262    } catch let error as ExpectationGroup.Failure {263      throw error // Propagate wrapped precondition error.264    } catch _ as Solution.Failure {265      // It's difficult to clearly determine which expectation is breaking the group, so instead266      // just throw an error at the group level instead.267      let allInvocations = getAllInvocations(in: contexts, after: nil)268      let failure = TestFailure.unsatisfiableExpectations(capturedExpectations: group.expectations,269                                                          allInvocations: allInvocations)270      throw ExpectationGroup.Failure(error: failure, sourceLocation: sourceLocation)271    } catch {272      fatalError("Unexpected error type") // This shouldn't happen.273    }274  }275  276  let queue = DispatchQueue(label: "co.bird.mockingbird.verify.inOrder")277  queue.setSpecific(key: ExpectationGroup.contextKey, value: group)278  queue.sync { scope() }279  280  do {281    try group.verify()282  } catch let error as ExpectationGroup.Failure {283    FailTest(String(describing: error),284             file: error.sourceLocation.file,285             line: error.sourceLocation.line)286  } catch {287    fatalError("Unexpected error type") // This shouldn't happen.288  }289}...

Full Screen

Full Screen

ExpectationGroup.swift

Source:ExpectationGroup.swift Github

copy

Full Screen

...26  struct Failure: Error {27    let error: TestFailure28    let sourceLocation: SourceLocation29  }30  func verify(context: ExpectationGroup? = nil) throws {31    if let parent = parent, context == nil {32      parent.addSubgroup(self)33    } else {34      try verificationBlock(self)35    }36  }37  38  private(set) var expectations = [CapturedExpectation]()39  func addExpectation(mockingContext: MockingContext,40                      invocation: Invocation,41                      expectation: Expectation) {42    expectations.append(CapturedExpectation(mockingContext: mockingContext,43                                            invocation: invocation,44                                            expectation: expectation))...

Full Screen

Full Screen

verify

Using AI Code Generation

copy

Full Screen

1let group = ExpectationGroup()2let expectation1 = group.expectation(description: "Expectation1")3let expectation2 = group.expectation(description: "Expectation2")4let expectation3 = group.expectation(description: "Expectation3")5let expectation4 = group.expectation(description: "Expectation4")6let expectation5 = group.expectation(description: "Expectation5")7let expectation6 = group.expectation(description: "Expectation6")8expectation1.fulfill()9expectation2.fulfill()10expectation3.fulfill()11expectation4.fulfill()12expectation5.fulfill()13expectation6.fulfill()14group.verify()15let group = ExpectationGroup()16let expectation1 = group.expectation(description: "Expectation1")17let expectation2 = group.expectation(description: "Expectation2")18let expectation3 = group.expectation(description: "Expectation3")19let expectation4 = group.expectation(description: "Expectation4")20let expectation5 = group.expectation(description: "Expectation5")21let expectation6 = group.expectation(description: "Expectation6")22expectation1.fulfill()23expectation2.fulfill()24expectation3.fulfill()25expectation4.fulfill()26expectation5.fulfill()27group.verify()28let group = ExpectationGroup()29let expectation1 = group.expectation(description: "Expectation1")30let expectation2 = group.expectation(description: "Expectation2")31let expectation3 = group.expectation(description: "Expectation3")32let expectation4 = group.expectation(description: "Expectation4")33let expectation5 = group.expectation(description: "Expectation5")34let expectation6 = group.expectation(description: "Expectation6")35expectation1.fulfill()36expectation2.fulfill()37expectation3.fulfill()38expectation4.fulfill()39expectation5.fulfill()40expectation6.fulfill()41group.verify()

Full Screen

Full Screen

verify

Using AI Code Generation

copy

Full Screen

1func testFunc() {2    let group = ExpectationGroup()3    let exp1 = group.expectation(description: "exp1")4    let exp2 = group.expectation(description: "exp2")5    let exp3 = group.expectation(description: "exp3")6    let exp4 = group.expectation(description: "exp4")7    let exp5 = group.expectation(description: "exp5")8    exp1.fulfill()9    exp2.fulfill()10    exp3.fulfill()11    exp4.fulfill()12    exp5.fulfill()13    group.verify()14}15func testFunc() {16    let group = ExpectationGroup()17    let exp1 = group.expectation(description: "exp1")18    let exp2 = group.expectation(description: "exp2")19    let exp3 = group.expectation(description: "exp3")20    let exp4 = group.expectation(description: "exp4")21    let exp5 = group.expectation(description: "exp5")22    exp1.fulfill()23    exp2.fulfill()24    exp3.fulfill()25    exp4.fulfill()26    exp5.fulfill()27    group.verify()28}29func testFunc() {30    let group = ExpectationGroup()31    let exp1 = group.expectation(description: "exp1")32    let exp2 = group.expectation(description: "exp2")33    let exp3 = group.expectation(description: "exp3")34    let exp4 = group.expectation(description: "exp4")35    let exp5 = group.expectation(description: "exp5")36    exp1.fulfill()37    exp2.fulfill()38    exp3.fulfill()39    exp4.fulfill()40    exp5.fulfill()41    group.verify()42}43func testFunc() {44    let group = ExpectationGroup()45    let exp1 = group.expectation(description: "exp1")46    let exp2 = group.expectation(description: "exp2")47    let exp3 = group.expectation(description: "exp3")48    let exp4 = group.expectation(description: "exp4")49    let exp5 = group.expectation(description: "exp5")

Full Screen

Full Screen

verify

Using AI Code Generation

copy

Full Screen

1import XCTest2class Test1: XCTestCase {3    func test1() {4        let exp = expectation(description: "test1")5        exp.fulfill()6        wait(for: [exp], timeout: 10)7    }8}9class Test2: XCTestCase {10    func test2() {11        let exp = expectation(description: "test2")12        exp.fulfill()13        wait(for: [exp], timeout: 10)14    }15}16let group = ExpectationGroup()17let test1 = Test1()18let test2 = Test2()19let testSuite = XCTestSuite(name: "testSuite")20testSuite.addTest(test1)21testSuite.addTest(test2)22XCTMain([testSuite])23group.verify()24	 Executed 2 tests, with 0 failures (0 unexpected) in 0.000 (0.000) seconds25	 Executed 2 tests, with 0 failures (0 unexpected) in 0.000 (0.000) seconds

Full Screen

Full Screen

verify

Using AI Code Generation

copy

Full Screen

1let group = ExpectationGroup()2let expectation1 = Expectation(description: "1")3let expectation2 = Expectation(description: "2")4group.add(expectation1)5group.add(expectation2)6expectation1.fulfill()7expectation2.fulfill()8group.verify()9let group = ExpectationGroup()10let expectation1 = Expectation(description: "1")11let expectation2 = Expectation(description: "2")12group.add(expectation1)13group.add(expectation2)14expectation1.fulfill()15expectation2.fulfill()16group.verify()17let group = ExpectationGroup()18let expectation1 = Expectation(description: "1")19let expectation2 = Expectation(description: "2")20group.add(expectation1)21group.add(expectation2)22expectation1.fulfill()23expectation2.fulfill()24group.verify()25let group = ExpectationGroup()26let expectation1 = Expectation(description: "1")27let expectation2 = Expectation(description: "2")28group.add(expectation1)29group.add(expectation2)30expectation1.fulfill()31expectation2.fulfill()32group.verify()33let group = ExpectationGroup()34let expectation1 = Expectation(description: "1")35let expectation2 = Expectation(description: "2")36group.add(expectation1)37group.add(expectation2)38expectation1.fulfill()39expectation2.fulfill()40group.verify()41let group = ExpectationGroup()42let expectation1 = Expectation(description: "1")43let expectation2 = Expectation(description: "2")44group.add(expectation1)45group.add(expectation2)46expectation1.fulfill()47expectation2.fulfill()48group.verify()49let group = ExpectationGroup()50let expectation1 = Expectation(description: "1")51let expectation2 = Expectation(description: "2")52group.add(expectation1)53group.add(expectation2)54expectation1.fulfill()55expectation2.fulfill()56group.verify()57let group = ExpectationGroup()58let expectation1 = Expectation(description: "1")59let expectation2 = Expectation(description: "2")60group.add(expectation1)61group.add(expectation2)62expectation1.fulfill()63expectation2.fulfill()64group.verify()

Full Screen

Full Screen

verify

Using AI Code Generation

copy

Full Screen

1let group = ExpectationGroup()2group.verify()3let group = ExpectationGroup()4group.verify()5Note: You can call verify() from any file, but you must call it from the same file it was created in. If you call verify() from a different file, the following error will be printed:6let group = ExpectationGroup()7group.verify()8let group = ExpectationGroup()9group.verify()10Note: You can call verify() from any file, but you must call it from the same file it was created in. If you call verify() from a different file, the following error will be printed:

Full Screen

Full Screen

verify

Using AI Code Generation

copy

Full Screen

1var group = ExpectationGroup()2group.verify()3var group = ExpectationGroup()4group.wait()5var group = ExpectationGroup()6group.wait(for: 1.0)7var group = ExpectationGroup()8group.wait(for: 1.0, enforceOrder: true)9var group = ExpectationGroup()10group.wait(for: 1.0, timeout: 10.0)11var group = ExpectationGroup()12group.wait(for: 1.0, timeout: 10.0, enforceOrder: true)

Full Screen

Full Screen

verify

Using AI Code Generation

copy

Full Screen

1import XCTest2class 1: XCTestCase {3    func testExample() {4        let group = ExpectationGroup()5        group.expectation(description: "test1") { expectation in6            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {7                expectation.fulfill()8            }9        }10        group.expectation(description: "test2") { expectation in11            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {12                expectation.fulfill()13            }14        }15        group.expectation(description: "test3") { expectation in16            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {17                expectation.fulfill()18            }19        }20        group.verify(timeout: 4) { error in21            XCTAssertNil(error)22        }23    }24}25import XCTest26class ExpectationGroup {27    private var expectations = [XCTestExpectation]()28    func expectation(description: String, closure: @escaping (XCTestExpectation) -> Void) {29        let expectation = XCTestExpectation(description: description)30        expectations.append(expectation)31        closure(expectation)32    }33    func verify(timeout: TimeInterval, closure: @escaping (Error?) -> Void) {34        let expectation = XCTestExpectation(description: "verify")35        DispatchQueue.main.asyncAfter(deadline: .now() + timeout) {36            if self.fulfillCount == self.expectations.count {37                expectation.fulfill()38            } else {39                closure(NSError(domain: "ExpectationGroup", code: -1, userInfo: nil))40            }41        }42        wait(for: [expectation], timeout: timeout + 1)43    }44    @objc private func fulfillExpectation() {45    }46}

Full Screen

Full Screen

verify

Using AI Code Generation

copy

Full Screen

1import XCTest2class ExpectationGroup: XCTestCase {3    func testExpectationGroup() {4        let group = DispatchGroup()5        let expectation = expectation(description: "expectation")6        let expectation1 = expectation(description: "expectation1")7        let expectation2 = expectation(description: "expectation2")8        let expectation3 = expectation(description: "expectation3")9        let expectation4 = expectation(description: "expectation4")10        let expectation5 = expectation(description: "expectation5")11        let expectation6 = expectation(description: "expectation6")12        let expectation7 = expectation(description: "expectation7")13        let expectation8 = expectation(description: "expectation8")14        let expectation9 = expectation(description: "expectation9")15        let expectation10 = expectation(description: "expectation10")16        let expectation11 = expectation(description: "expectation11")17        let expectation12 = expectation(description: "expectation12")18        let expectation13 = expectation(description: "expectation13")19        let expectation14 = expectation(description: "expectation14")20        let expectation15 = expectation(description: "expectation15")21        let expectation16 = expectation(description: "expectation16")22        let expectation17 = expectation(description: "expectation17")23        let expectation18 = expectation(description: "expectation18")24        let expectation19 = expectation(description: "expectation19")25        let expectation20 = expectation(description: "expectation20")26        let expectation21 = expectation(description: "expectation21")27        let expectation22 = expectation(description: "expectation22")28        let expectation23 = expectation(description: "expectation23")29        let expectation24 = expectation(description: "expectation24")30        let expectation25 = expectation(description: "expectation25")31        let expectation26 = expectation(description: "expectation26")32        let expectation27 = expectation(description: "expectation27")33        let expectation28 = expectation(description: "expectation28")34        let expectation29 = expectation(description: "expectation29")35        let expectation30 = expectation(description: "expectation30")36        let expectation31 = expectation(description: "expectation31")37        let expectation32 = expectation(description: "expectation32")38        let expectation33 = expectation(description: "expectation33")39        let expectation34 = expectation(description: "expectation34")40        let expectation35 = expectation(description: "expectation35")

Full Screen

Full Screen

verify

Using AI Code Generation

copy

Full Screen

1import XCTest2import XCTestExpectationGroup3class Tests: XCTestCase {4    func testExample() {5        let expectationGroup = ExpectationGroup()6        let expectation1 = expectation(description: "expectation1")7        let expectation2 = expectation(description: "expectation2")8        let expectation3 = expectation(description: "expectation3")9        expectationGroup.add(expectation: expectation1)10        expectationGroup.add(expectation: expectation2)11        expectationGroup.add(expectation: expectation3)12        expectationGroup.verify()13    }14}15import XCTest16import XCTestExpectationGroup17class Tests: XCTestCase {18    func testExample() {19        let expectationGroup = ExpectationGroup()20        let expectation1 = expectation(description: "expectation1")21        let expectation2 = expectation(description: "expectation2")22        let expectation3 = expectation(description: "expectation3")23        expectationGroup.add(expectation: expectation1)24        expectationGroup.add(expectation: expectation2)25        expectationGroup.add(expectation: expectation3)26        expectationGroup.verify(timeout: 10)27    }28}29import XCTest30import XCTestExpectationGroup31class Tests: XCTestCase {32    func testExample() {33        let expectationGroup = ExpectationGroup()34        let expectation1 = expectation(description: "expectation1")35        let expectation2 = expectation(description: "expectation2")36        let expectation3 = expectation(description: "expectation3")37        expectationGroup.add(expectation: expectation1

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockingbird automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in ExpectationGroup

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful