---
title: "keyValueObservingExpectation(for:keyPath:handler:)"
framework: xctest
role: symbol
role_heading: Instance Method
path: "xctest/xctestcase/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.

## Declaration

```swift
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 doc://com.apple.xctest/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

Discussion Creates an 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 true (to fulfill the expectation), or the wait times out. You can use XCTAssert and related APIs in the block to report a failure. note: For more control over KVO-based expectations, use XCTKVOExpectation instead of this convenience method.

## See Also

### Creating Asynchronous Test Expectations

- [expectation(description:)](xctest/xctestcase/expectation(description:).md)
- [expectation(for:evaluatedWith:handler:)](xctest/xctestcase/expectation(for:evaluatedwith:handler:).md)
- [expectation(forNotification:object:handler:)](xctest/xctestcase/expectation(fornotification:object:handler:).md)
- [expectation(forNotification:object:notificationCenter:handler:)](xctest/xctestcase/expectation(fornotification:object:notificationcenter:handler:).md)
- [keyValueObservingExpectation(for:keyPath:expectedValue:)](xctest/xctestcase/keyvalueobservingexpectation(for:keypath:expectedvalue:).md)
- [expectation(that:on:options:willEqual:)](xctest/xctestcase/expectation(that:on:options:willequal:).md)
- [expectation(that:on:options:willSatisfy:)](xctest/xctestcase/expectation(that:on:options:willsatisfy:)-6itb.md)
- [expectation(that:on:options:willSatisfy:)](xctest/xctestcase/expectation(that:on:options:willsatisfy:)-292oj.md)
- [expectation(that:on:options:willSatisfy:)](xctest/xctestcase/expectation(that:on:options:willsatisfy:)-85or0.md)
