<!--
{
  "availability" : [
    "iOS: -",
    "iPadOS: -",
    "macCatalyst: -",
    "macOS: -",
    "tvOS: -",
    "visionOS: -",
    "watchOS: -"
  ],
  "documentType" : "symbol",
  "framework" : "XCTest",
  "identifier" : "/documentation/XCTest/XCTestCase/keyValueObservingExpectation(for:keyPath:handler:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "XCTest"
    ],
    "preciseIdentifier" : "c:objc(cs)XCTestCase(im)keyValueObservingExpectationForObject:keyPath:handler:"
  },
  "title" : "keyValueObservingExpectation(for:keyPath:handler:)"
}
-->

# keyValueObservingExpectation(for:keyPath:handler:)

Creates an expectation that uses Key-Value Observing to observe a value and respond to changes in that value by calling a provided handler.

```
func keyValueObservingExpectation(for objectToObserve: Any, keyPath: String, handler: XCTKVOExpectation.Handler? = nil) -> XCTestExpectation
```

## Parameters

`objectToObserve`

The object to observe.

`keyPath`

The key path to observe.

`handler`

An optional [`XCTKVOExpectation.Handler`](/documentation/XCTest/XCTKVOExpectation/Handler-swift.typealias) block. If you don’t provide a handler block, the first change to the key path of the observed object fulfills the expectation.

## Discussion

Creates an [`XCTestExpectation`](/documentation/XCTest/XCTestExpectation) that uses Key Value Observing to observe changes on the value specified by `keyPath` on the provided object.

When the tests detects changes to the value, it calls the `handler` block to assess the new value to see if the change fulfills the expectation. Every key-value observing change runs the handler block until it either returns <doc://com.apple.documentation/documentation/Swift/true> (to fulfill the expectation), or the wait times out.

You can use [`XCTAssert`](/documentation/XCTest/XCTAssert) and related APIs in the block to report a failure.

> Note:
> For more control over KVO-based expectations, use ``doc://com.apple.xctest/documentation/XCTest/XCTKVOExpectation`` instead of this convenience method.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)