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

# keyValueObservingExpectation(for:keyPath:expectedValue:)

Creates an expectation that uses Key-Value Observing to observe a value until it matches an expected value.

```
func keyValueObservingExpectation(for objectToObserve: Any, keyPath: String, expectedValue: Any?) -> XCTestExpectation
```

## Parameters

`objectToObserve`

The object to observe.

`keyPath`

The key path to observe.

`expectedValue`

Expected value of the value specified by `keyPath`. The expectation will fulfill itself when the value at `keyPath` is equal to `expectedValue`, as tested using `isEqual:`. If `expectedValue` is `nil`, the expectation will be fulfilled by the first change to the key path of the observed object.

## Return Value

Creates and returns an expectation associated with the test case.

## Discussion

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

> 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)