pub struct XCTestCase { /* private fields */ }Expand description
XCTestCase is a concrete subclass of XCTest that should be the override point for most developers creating tests for their projects. A test case subclass can have multiple test methods and supports setup and tear down that executes for every test method as well as class level setup and tear down.
To define a test case:
• Create a subclass of XCTestCase. • Implement -test methods. • Optionally define instance variables or properties that store the state of the test. • Optionally initialize state by overriding -setUp • Optionally clean-up after a test by overriding -tearDown.
Test methods are instance methods meeting these requirements: • accepting no parameters • returning no value • prefixed with ‘test’
For example:
- (void)testSomething;
Test methods are automatically recognized as test cases by the XCTest framework. Each XCTestCase subclass’s defaultTestSuite is a XCTestSuite which includes these tests. Test method implementations usually contain assertions that must be verified for the test to pass, for example:
@interface MathTest : XCTestCase
@property float f1;
@property float f2;
@end
@implementation MathTest
- (void)setUp
{
self.f1 = 2.0;
self.f2 = 3.0;
}
- (void)testAddition
{
XCTAssertTrue(f1 + f2 == 5.0);
}
@end
See also Apple’s documentation
Implementations§
Source§impl XCTestCase
impl XCTestCase
pub unsafe fn testCaseWithInvocation( invocation: Option<&NSInvocation>, ) -> Retained<Self>
pub unsafe fn initWithInvocation( this: Allocated<Self>, invocation: Option<&NSInvocation>, ) -> Retained<Self>
Sourcepub unsafe fn testCaseWithSelector(selector: Sel) -> Option<Retained<Self>>
pub unsafe fn testCaseWithSelector(selector: Sel) -> Option<Retained<Self>>
§Safety
selector must be a valid selector.
Sourcepub unsafe fn initWithSelector(
this: Allocated<Self>,
selector: Sel,
) -> Retained<Self>
pub unsafe fn initWithSelector( this: Allocated<Self>, selector: Sel, ) -> Retained<Self>
§Safety
selector must be a valid selector.
Sourcepub unsafe fn invocation(&self) -> Option<Retained<NSInvocation>>
pub unsafe fn invocation(&self) -> Option<Retained<NSInvocation>>
The invocation used when this test is run.
Sourcepub unsafe fn setInvocation(&self, invocation: Option<&NSInvocation>)
pub unsafe fn setInvocation(&self, invocation: Option<&NSInvocation>)
Setter for invocation.
Sourcepub fn invokeTest(&self)
pub fn invokeTest(&self)
Invoking a test performs its setUp, invocation, and tearDown. In general this should not be called directly.
Sourcepub fn continueAfterFailure(&self) -> bool
pub fn continueAfterFailure(&self) -> bool
Determines whether the test method continues execution after an XCTAssert fails.
By default, this property is YES, meaning the test method will complete regardless of how many XCTAssert failures occur. Setting this to NO causes the test method to end execution immediately after the first failure occurs, but does not affect remaining test methods in the suite.
If XCTAssert failures in the test method indicate problems with state or determinism, additional
failures may be not be helpful information. Setting continueAfterFailure to NO can reduce the
noise in the test report for these kinds of tests.
Sourcepub fn setContinueAfterFailure(&self, continue_after_failure: bool)
pub fn setContinueAfterFailure(&self, continue_after_failure: bool)
Setter for continueAfterFailure.
Sourcepub fn recordIssue(&self, issue: &XCTIssue)
pub fn recordIssue(&self, issue: &XCTIssue)
Records a failure or other issue in the execution of the test and is used by all test assertions. Overrides of this method should call super unless they wish to suppress the issue. Super can be invoked with a different issue object.
Parameter issue: Object with all details related to the issue.
Sourcepub fn testInvocations() -> Retained<NSArray<NSInvocation>>
pub fn testInvocations() -> Retained<NSArray<NSInvocation>>
Invocations for each test method in the test case.
Sourcepub fn addTeardownBlock(&self, block: &DynBlock<dyn Fn()>)
Available on crate feature block2 only.
pub fn addTeardownBlock(&self, block: &DynBlock<dyn Fn()>)
block2 only.Registers a block to be run at the end of a test.
Teardown blocks are executed after the current test method has returned but before -tearDown is invoked.
Registered blocks are run on the main thread but can be registered from any thread. They are guaranteed to run only once, in LIFO order, and are executed serially. You may register blocks during -setUp, but you may not register blocks during -tearDown or from other teardown blocks.
Parameter block: A block to enqueue for future execution.
Sourcepub unsafe fn addAsyncTeardownBlock(
&self,
block: &DynBlock<dyn Fn(NonNull<DynBlock<dyn Fn(*mut NSError)>>)>,
)
Available on crate feature block2 only.
pub unsafe fn addAsyncTeardownBlock( &self, block: &DynBlock<dyn Fn(NonNull<DynBlock<dyn Fn(*mut NSError)>>)>, )
block2 only.Registers an async block to be run at the end of a test.
Teardown blocks are executed after the current test method has returned but before -tearDown is invoked.
Registered blocks are run on the main thread but can be registered from any thread. They are guaranteed to run only once, in LIFO order, and are executed serially. You may register blocks during -setUp, but you may not register blocks during -tearDown or from other teardown blocks.
Parameter block: An async block to enqueue for future execution. The completion handler
passed to this block must be invoked for test execution to continue. Invoking the completion
handler with a non-nil NSError will cause an XCTIssue to be recorded representing the error.
§Safety
block block’s argument block’s argument must be a valid pointer or null.
Sourcepub fn executionTimeAllowance(&self) -> NSTimeInterval
pub fn executionTimeAllowance(&self) -> NSTimeInterval
If test timeouts are enabled, this property represents the amount of time the test would like to be given to run. If the test exceeds its allowance, Xcode will capture a spindump of the process and then restart it so that test execution can continue on with the next test. The test that timed out will be marked as a failure, and the spindump will be attached to the test in Xcode’s test report.
Note that the value you supply will be rounded up to the nearest minute value. Also note that a test may be given less time than the value you specify if the -maximum-test-execution-time-allowance option is passed to xcodebuild.
The default value is 10 minutes.
Sourcepub fn setExecutionTimeAllowance(
&self,
execution_time_allowance: NSTimeInterval,
)
pub fn setExecutionTimeAllowance( &self, execution_time_allowance: NSTimeInterval, )
Setter for executionTimeAllowance.
Source§impl XCTestCase
Methods declared on superclass NSObject.
impl XCTestCase
Methods declared on superclass NSObject.
Source§impl XCTestCase
XCTestSuiteExtensions.
impl XCTestCase
XCTestSuiteExtensions.
Sourcepub fn defaultTestSuite() -> Retained<XCTestSuite>
pub fn defaultTestSuite() -> Retained<XCTestSuite>
Returns a test suite containing test cases for all of the tests in the class.
impl XCTestCase
XCTActivity.
XCTestCase conforms to XCTActivity, allowing test attachments to be added directly from test methods.
See XCTAttachment.h for details on how to create attachments. Once created, they can be added directly to XCTestCase:
- (void)testFoo
{
XCTAttachment *attachment = ...
[self addAttachment:attachment];
}
Source§impl XCTestCase
XCTPerformanceAnalysis.
impl XCTestCase
XCTPerformanceAnalysis.
Interface extension for measure related API.
Sourcepub fn defaultPerformanceMetrics() -> Retained<NSArray<XCTPerformanceMetric>>
pub fn defaultPerformanceMetrics() -> Retained<NSArray<XCTPerformanceMetric>>
The names of the performance metrics to measure when invoking -measureBlock:. Returns XCTPerformanceMetric_WallClockTime by default. Subclasses can override this to change the behavior of -measureBlock:
Sourcepub fn measureBlock(&self, block: &DynBlock<dyn Fn() + '_>)
Available on crate feature block2 only.
pub fn measureBlock(&self, block: &DynBlock<dyn Fn() + '_>)
block2 only.Call from a test method to measure resources (+defaultPerformanceMetrics) used by the block in the current process.
- (void)testPerformanceOfMyFunction {
[self measureBlock:^{ // Do that thing you want to measure. MyFunction(); }]; }
Parameter block: A block whose performance to measure.
Sourcepub fn measureMetrics_automaticallyStartMeasuring_forBlock(
&self,
metrics: &NSArray<XCTPerformanceMetric>,
automatically_start_measuring: bool,
block: &DynBlock<dyn Fn() + '_>,
)
Available on crate feature block2 only.
pub fn measureMetrics_automaticallyStartMeasuring_forBlock( &self, metrics: &NSArray<XCTPerformanceMetric>, automatically_start_measuring: bool, block: &DynBlock<dyn Fn() + '_>, )
block2 only.Call from a test method to measure resources (XCTPerformanceMetrics) used by the block in the current process. Each metric will be measured across calls to the block. The number of times the block will be called is undefined and may change in the future. For one example of why, as long as the requested performance metrics do not interfere with each other the API will measure all metrics across the same calls to the block. If the performance metrics may interfere the API will measure them separately.
- (void)testMyFunction2_WallClockTime { [self measureMetrics:[self class].defaultPerformanceMetrics automaticallyStartMeasuring:NO forBlock:^{
// Do setup work that needs to be done for every iteration but you don’t want to measure before the call to -startMeasuring SetupSomething(); [self startMeasuring];
// Do that thing you want to measure. MyFunction(); [self stopMeasuring];
// Do teardown work that needs to be done for every iteration but you don’t want to measure after the call to -stopMeasuring TeardownSomething(); }]; }
Caveats: • If YES was passed for automaticallyStartMeasuring and -startMeasuring is called anyway, the test will fail. • If NO was passed for automaticallyStartMeasuring then -startMeasuring must be called once and only once before the end of the block or the test will fail. • If -stopMeasuring is called multiple times during the block the test will fail.
Parameter metrics: An array of NSStrings (XCTPerformanceMetrics) to measure. Providing an unrecognized string is a test failure.
Parameter automaticallyStartMeasuring: If NO, XCTestCase will not take any measurements until -startMeasuring is called.
Parameter block: A block whose performance to measure.
Sourcepub fn startMeasuring(&self)
pub fn startMeasuring(&self)
Call this from within a measure block to set the beginning of the critical section. Measurement of metrics will start at this point.
Sourcepub fn stopMeasuring(&self)
pub fn stopMeasuring(&self)
Call this from within a measure block to set the ending of the critical section. Measurement of metrics will stop at this point.
Sourcepub fn defaultMetrics() -> Retained<NSArray<ProtocolObject<dyn XCTMetric>>>
pub fn defaultMetrics() -> Retained<NSArray<ProtocolObject<dyn XCTMetric>>>
A collection of metrics to be taken by default when -measureBlock or -measureWithOptions:block: is called.
Sourcepub fn defaultMeasureOptions() -> Retained<XCTMeasureOptions>
pub fn defaultMeasureOptions() -> Retained<XCTMeasureOptions>
Collection of configurable settings to change how measurements are taken.
Sourcepub fn measureWithMetrics_block(
&self,
metrics: &NSArray<ProtocolObject<dyn XCTMetric>>,
block: &DynBlock<dyn Fn() + '_>,
)
Available on crate feature block2 only.
pub fn measureWithMetrics_block( &self, metrics: &NSArray<ProtocolObject<dyn XCTMetric>>, block: &DynBlock<dyn Fn() + '_>, )
block2 only.Measures the block using the provided metrics and the default options from your XCTestCase class.
Parameter metrics: A non-empty array of objects which adopt the XCTMetric protocol, describing the set of metrics to measure.
Parameter block: The block to be measured.
Sourcepub fn measureWithOptions_block(
&self,
options: &XCTMeasureOptions,
block: &DynBlock<dyn Fn() + '_>,
)
Available on crate feature block2 only.
pub fn measureWithOptions_block( &self, options: &XCTMeasureOptions, block: &DynBlock<dyn Fn() + '_>, )
block2 only.Measures the block using the default metrics from your XCTestCase class and the provided options.
Parameter options: An object describing the options to use when measuring the block, such as the number of times the block should be executed.
Parameter block: The block to be measured.
See also: XCTMeasureOptions
Sourcepub fn measureWithMetrics_options_block(
&self,
metrics: &NSArray<ProtocolObject<dyn XCTMetric>>,
options: &XCTMeasureOptions,
block: &DynBlock<dyn Fn() + '_>,
)
Available on crate feature block2 only.
pub fn measureWithMetrics_options_block( &self, metrics: &NSArray<ProtocolObject<dyn XCTMetric>>, options: &XCTMeasureOptions, block: &DynBlock<dyn Fn() + '_>, )
block2 only.Measures the block using the provided metrics and options.
Parameter metrics: A non-empty array of objects which adopt the XCTMetric protocol, describing the set of metrics to measure.
Parameter options: An object describing the options to use when measuring the block, such as the number of times the block should be executed.
Parameter block: The block to be measured.
Source§impl XCTestCase
XCTDeprecated.
impl XCTestCase
XCTDeprecated.
Sourcepub fn recordFailureWithDescription_inFile_atLine_expected(
&self,
description: &NSString,
file_path: &NSString,
line_number: NSUInteger,
expected: bool,
)
👎Deprecated
pub fn recordFailureWithDescription_inFile_atLine_expected( &self, description: &NSString, file_path: &NSString, line_number: NSUInteger, expected: bool, )
Records a failure in the execution of the test.
This method is deprecated and has been replaced by the -recordIssue: method and XCTIssue class, which
provide greater flexibility for recording issues that arise during testing. Overriding this method in an XCTestCase subclass and
modifying its arguments before calling super may cause information about the failure to be lost and is not recommended.
Instead, override -recordIssue: and pass super a modified XCTIssue.
Parameter description: The description of the failure being recorded. When replacing usage of this deprecated API,
this can be represented using the compactDescription property on XCTIssue.
Parameter filePath: The file path to the source file where the failure being recorded was encountered.
When replacing usage of this deprecated API, this can be specified using an XCTSourceCodeLocation instance
associated with an XCTIssue via its sourceCodeContext property.
Parameter lineNumber: The line number in the source file at filePath where the failure being recorded
was encountered. When replacing usage of this deprecated API, this can be specified using an XCTSourceCodeLocation
instance associated with an XCTIssue via its sourceCodeContext property.
Parameter expected: NO if the failure being recorded was the result of an uncaught exception, YES if it was the result
of a failed assertion or any other reason. When replacing usage of this deprecated API, the representation using XCTIssue may vary.
A NO value may be specified using the issue type XCTIssueTypeUncaughtException, and a YES value may be represented
using a different issue type such as XCTIssueTypeAssertionFailure combined with other properties on XCTIssue.
Source§impl XCTestCase
AsynchronousTesting.
impl XCTestCase
AsynchronousTesting.
This category introduces support for asynchronous testing in XCTestCase. The mechanism allows you to specify one or more “expectations” that will occur asynchronously as a result of actions in the test. Once all expectations have been set, a “wait” API is called that will block execution of subsequent test code until all expected conditions have been fulfilled or a timeout occurs.
Sourcepub fn expectationWithDescription(
&self,
description: &NSString,
) -> Retained<XCTestExpectation>
pub fn expectationWithDescription( &self, description: &NSString, ) -> Retained<XCTestExpectation>
Parameter description: This string will be displayed in the test log to help diagnose failures.
Creates and returns an expectation associated with the test case.
Sourcepub unsafe fn waitForExpectationsWithTimeout_handler(
&self,
timeout: NSTimeInterval,
handler: XCWaitCompletionHandler,
mtm: MainThreadMarker,
)
Available on crate feature block2 only.
pub unsafe fn waitForExpectationsWithTimeout_handler( &self, timeout: NSTimeInterval, handler: XCWaitCompletionHandler, mtm: MainThreadMarker, )
block2 only.Parameter timeout: The amount of time within which all expectations must be fulfilled.
Parameter handler: If provided, the handler will be invoked both on timeout or fulfillment of all
expectations. Timeout is always treated as a test failure.
-waitForExpectationsWithTimeout:handler: creates a point of synchronization in the flow of a test. Only one -waitForExpectationsWithTimeout:handler: can be active at any given time, but multiple discrete sequences of { expectations -> wait } can be chained together.
-waitForExpectationsWithTimeout:handler: runs the run loop while handling events until all expectations are fulfilled or the timeout is reached. Clients should not manipulate the run loop while using this API.
§Safety
handler must be a valid pointer or null.
Sourcepub fn waitForExpectations(&self, expectations: &NSArray<XCTestExpectation>)
pub fn waitForExpectations(&self, expectations: &NSArray<XCTestExpectation>)
Waits on a group of expectations indefinitely.
Parameter expectations: An array of expectations that must be fulfilled.
The test will continue to run until _expectations_are fulfilled or the test reaches its execution time allowance.
Expectations can only appear in the list once. This method may return early based on fulfillment of the provided expectations.
Enabling test timeouts is recommended when using this method to prevent a runaway expectation from hanging the test.
Sourcepub fn waitForExpectations_timeout(
&self,
expectations: &NSArray<XCTestExpectation>,
seconds: NSTimeInterval,
)
pub fn waitForExpectations_timeout( &self, expectations: &NSArray<XCTestExpectation>, seconds: NSTimeInterval, )
Waits on a group of expectations for up to the specified timeout.
Parameter expectations: An array of expectations that must be fulfilled.
Parameter seconds: The number of seconds within which all expectations must be fulfilled.
Expectations can only appear in the list once. This method may return early based on fulfillment of the provided expectations.
Sourcepub fn waitForExpectations_enforceOrder(
&self,
expectations: &NSArray<XCTestExpectation>,
enforce_order_of_fulfillment: bool,
)
pub fn waitForExpectations_enforceOrder( &self, expectations: &NSArray<XCTestExpectation>, enforce_order_of_fulfillment: bool, )
Waits on a group of expectations indefinitely, optionally enforcing their order of fulfillment.
Parameter expectations: An array of expectations that must be fulfilled.
Parameter enforceOrderOfFulfillment: If
YES,the expectations specified by the
_expectations_parameter must
be satisfied in the order they appear in the array.
The test will continue to run until _expectations_are fulfilled or the test reaches its execution time allowance.
Expectations can only appear in the list once. This method may return early based on fulfillment of the provided expectations.
Enabling test timeouts is recommended when using this method to prevent a runaway expectation from hanging the test.
Sourcepub fn waitForExpectations_timeout_enforceOrder(
&self,
expectations: &NSArray<XCTestExpectation>,
seconds: NSTimeInterval,
enforce_order_of_fulfillment: bool,
)
pub fn waitForExpectations_timeout_enforceOrder( &self, expectations: &NSArray<XCTestExpectation>, seconds: NSTimeInterval, enforce_order_of_fulfillment: bool, )
Waits on a group of expectations for up to the specified timeout, optionally enforcing their order of fulfillment.
Parameter expectations: An array of expectations that must be fulfilled.
Parameter seconds: The number of seconds within which all expectations must be fulfilled.
Parameter enforceOrderOfFulfillment: If
YES,the expectations specified by the
_expectations_parameter must
be satisfied in the order they appear in the array.
Expectations can only appear in the list once. This method may return early based on fulfillment of the provided expectations.
Sourcepub unsafe fn keyValueObservingExpectationForObject_keyPath_expectedValue(
&self,
object_to_observe: &AnyObject,
key_path: &NSString,
expected_value: Option<&AnyObject>,
) -> Retained<XCTestExpectation>
pub unsafe fn keyValueObservingExpectationForObject_keyPath_expectedValue( &self, object_to_observe: &AnyObject, key_path: &NSString, expected_value: Option<&AnyObject>, ) -> Retained<XCTestExpectation>
A convenience method for asynchronous tests that use Key Value Observing to detect changes to values on an object. This variant takes an expected value and observes changes on the object until the keyPath’s value matches the expected value using -[NSObject isEqual:]. If other comparisons are needed, use the variant below that takes a handler block.
Parameter objectToObserve: The object to observe.
Parameter keyPath: The key path to observe.
Parameter expectedValue: Expected value of the keyPath for the object. The expectation will fulfill itself when the
keyPath is equal, as tested using -[NSObject isEqual:]. If nil, the expectation will be
fulfilled by the first change to the key path of the observed object.
Returns: Creates and returns an expectation associated with the test case.
§Safety
object_to_observeshould be of the correct type.expected_valueshould be of the correct type.
Sourcepub unsafe fn keyValueObservingExpectationForObject_keyPath_handler(
&self,
object_to_observe: &AnyObject,
key_path: &NSString,
handler: XCKeyValueObservingExpectationHandler,
) -> Retained<XCTestExpectation>
Available on crate feature block2 only.
pub unsafe fn keyValueObservingExpectationForObject_keyPath_handler( &self, object_to_observe: &AnyObject, key_path: &NSString, handler: XCKeyValueObservingExpectationHandler, ) -> Retained<XCTestExpectation>
block2 only.Variant of the convenience for tests that use Key Value Observing. Takes a handler block instead of an expected value. Every KVO change will run the handler block until it returns YES (or the wait times out). Returning YES from the block will fulfill the expectation. XCTAssert and related APIs can be used in the block to report a failure.
Parameter objectToObserve: The object to observe.
Parameter keyPath: The key path to observe.
Parameter handler: Optional handler, /see XCKeyValueObservingExpectationHandler. If not provided, the expectation will
be fulfilled by the first change to the key path of the observed object.
Returns: Creates and returns an expectation associated with the test case.
§Safety
object_to_observeshould be of the correct type.handlermust be a valid pointer or null.
Sourcepub unsafe fn expectationForNotification_object_handler(
&self,
notification_name: &NSNotificationName,
object_to_observe: Option<&AnyObject>,
handler: XCNotificationExpectationHandler,
) -> Retained<XCTestExpectation>
Available on crate feature block2 only.
pub unsafe fn expectationForNotification_object_handler( &self, notification_name: &NSNotificationName, object_to_observe: Option<&AnyObject>, handler: XCNotificationExpectationHandler, ) -> Retained<XCTestExpectation>
block2 only.A convenience method for asynchronous tests that observe NSNotifications from the default NSNotificationCenter.
Parameter notificationName: The notification to register for.
Parameter objectToObserve: The object to observe.
Parameter handler: Optional handler, /see XCNotificationExpectationHandler. If not provided, the expectation
will be fulfilled by the first notification matching the specified name from the
observed object.
Returns: Creates and returns an expectation associated with the test case.
§Safety
object_to_observeshould be of the correct type.handlermust be a valid pointer or null.
Sourcepub unsafe fn expectationForNotification_object_notificationCenter_handler(
&self,
notification_name: &NSNotificationName,
object_to_observe: Option<&AnyObject>,
notification_center: &NSNotificationCenter,
handler: XCNotificationExpectationHandler,
) -> Retained<XCTestExpectation>
Available on crate feature block2 only.
pub unsafe fn expectationForNotification_object_notificationCenter_handler( &self, notification_name: &NSNotificationName, object_to_observe: Option<&AnyObject>, notification_center: &NSNotificationCenter, handler: XCNotificationExpectationHandler, ) -> Retained<XCTestExpectation>
block2 only.A convenience method for asynchronous tests that observe NSNotifications from a specific NSNotificationCenter.
Parameter notificationName: The notification to register for.
Parameter objectToObserve: The object to observe.
Parameter notificationCenter: The notification center from which to observe the notification.
Parameter handler: Optional handler, /see XCNotificationExpectationHandler. If not provided, the expectation
will be fulfilled by the first notification matching the specified name from the
observed object.
Returns: Creates and returns an expectation associated with the test case.
§Safety
object_to_observeshould be of the correct type.handlermust be a valid pointer or null.
Sourcepub unsafe fn expectationForPredicate_evaluatedWithObject_handler(
&self,
predicate: &NSPredicate,
object: Option<&AnyObject>,
handler: XCPredicateExpectationHandler,
) -> Retained<XCTestExpectation>
Available on crate feature block2 only.
pub unsafe fn expectationForPredicate_evaluatedWithObject_handler( &self, predicate: &NSPredicate, object: Option<&AnyObject>, handler: XCPredicateExpectationHandler, ) -> Retained<XCTestExpectation>
block2 only.Creates an expectation that is fulfilled if the predicate returns true when evaluated with the given object. The expectation periodically evaluates the predicate and also may use notifications or other events to optimistically re-evaluate.
When the resulting expectation is used from Swift and is awaited using
fulfillment(of:)rather
than
wait(for:),XCTest evaluates
_predicate_on the main actor.
§Safety
objectshould be of the correct type.handlermust be a valid pointer or null.
Source§impl XCTestCase
XCUIApplication_LaunchTesting.
impl XCTestCase
XCUIApplication_LaunchTesting.
Sourcepub fn runsForEachTargetApplicationUIConfiguration() -> bool
pub fn runsForEachTargetApplicationUIConfiguration() -> bool
Determines whether the tests in this class should run multiple times, once for each of the target application’s UI configurations.
Returns false by default. If overridden in a UI test subclass to return true, each test in that class will run multiple times, once for each supported UI configuration of the default target application.
Supported UI configurations are detected by Xcode according to the settings of the default target app for the UI test target and may include:
- Appearances (e.g. light mode, dark mode)
- Orientations (e.g. portrait, landscape)
- Localizations (e.g. en_US, zh_CN)
Given the above example, one UI configuration would be {dark mode, landscape, en_US}, another would be
{light mode, portrait, zh_CN}, and so forth. The number of combinations determines the number of times each
test will run. The UI configuration is used automatically when calling XCUIApplication.launch() in each test.
Source§impl XCTestCase
XCUIInterruptionMonitoring.
impl XCTestCase
XCUIInterruptionMonitoring.
Sourcepub fn addUIInterruptionMonitorWithDescription_handler(
&self,
handler_description: &NSString,
handler: &DynBlock<dyn Fn(NonNull<XCUIElement>) -> Bool>,
) -> Retained<ProtocolObject<dyn NSObjectProtocol>>
Available on crate features block2 and objc2-xc-ui-automation only.
pub fn addUIInterruptionMonitorWithDescription_handler( &self, handler_description: &NSString, handler: &DynBlock<dyn Fn(NonNull<XCUIElement>) -> Bool>, ) -> Retained<ProtocolObject<dyn NSObjectProtocol>>
block2 and objc2-xc-ui-automation only.Adds a monitor to the test. Monitors are automatically removed at the end of the test or can be manually removed using -removeUIInterruptionMonitor:. Monitors are invoked in the reverse order in which they are added until one of the monitors returns true, indicating that it has handled the interruption.
Parameter handlerDescription: Explanation of the behavior and purpose of this monitor, mainly used for debugging and analysis.
Parameter handler: Handler block for asynchronous, non-deterministic interrupting UI such as alerts and other dialogs. Handlers should return true if they handled the UI, false if they did not.
The handler is passed an XCUIElement representing the top level UI element for the alert.
Returns: Returns an opaque token that can be used to remove the monitor.
A “UI interruption” is any element which unexpectedly blocks access to an element with which a UI test is trying to interact. Interrupting elements are most commonly alerts, dialogs, or other windows, but can be of other types as well. Interruptions are unexpected or at least not deterministic: the appearance of an alert in direct response to a test action such as clicking a button is not an interruption and should not be handled using a UI interruption monitor. Instead, it’s simply part of the UI and should be found using standard queries and interacted with using standard event methods. Note that some interruptions are part of the app’s own UI, others are presented on behalf of system apps and services, so queries for these elements must be constructed with the right process at their root.
Use a UI interruption monitor for alerts that appear unexpectedly or with non-deterministic timing. Monitors are not invoked simply by the appearance of an alert or similar UI, they are called when the presence of such UI interferes with actions the test is attempting to take. For example, consider the following sequence:
- test taps button
- app displays confirmation dialog
In this case, the dialog that is presented can be anticipated by the test, so a UI interruption monitor should not be used. Instead, the sequence should look like:
- test taps button
- test constructs an XCUIElement for the dialog and uses XCUIElement.waitForExistence(timeout:) to wait for it to appear
- app displays confirmation dialog
- test synthesizes a tap for the appropriate button in the dialog
- test continues execution
There was no UI interruption in this example because every step was deterministic and known in advance. Note the use of XCUIElement.waitForExistence(timeout:) to deal with asynchronous delays in the display of the dialog.
By contrast, consider the next sequence, where use of a UI interruption monitor is the correct solution:
- test launches app
- app initiates asynchronous network request
- test interacts with app
- network request completes, app decides to display a dialog to the user
- dialog appears just as the test is about to tap on a button
- the appearance of the dialog is not deterministic
- the test can anticipate that the dialog might be displayed at some point, but not when
- accordingly, the test has installed a UI interruption monitor that knows how to handle the network response dialog
- when XCTest computes a hit point for the button, it discovers the dialog and treats it as “interrupting UI”
- the previously installed UI interruption monitor is invoked
- it handles the dialog
- XCTest computes the hit point for the button and synthesizes the requested tap event
- test execution continues…
Monitors can be designed to be general or specific in how they handle interruptions. The simplest general approach might simply attempt to cancel/dismiss/close any interrupting dialog/alert/window without consideration for its contents or purpose. A more specific monitor might make decisions based on the UI and contents of the interruption. Tests may install multiple monitors, which will be invoked in reverse order of installation. If a more specific monitor wishes to be skipped for a given interruption, its handler can simply return false - the next monitor will be invoked, and so on, until one of them returns true, signifying that it has handled the interruption. In some cases, a default monitor may handle interruptions.
Sourcepub unsafe fn removeUIInterruptionMonitor(
&self,
monitor: &ProtocolObject<dyn NSObjectProtocol>,
)
pub unsafe fn removeUIInterruptionMonitor( &self, monitor: &ProtocolObject<dyn NSObjectProtocol>, )
Removes a monitor using the token provided when it was added.
Parameter monitor: The token representing the monitor returned from the call to addUIInterruptionMonitorWithDescription:handler: where it was registered.
§Safety
monitor should be of the correct type.
Methods from Deref<Target = XCTest>§
Sourcepub fn testCaseCount(&self) -> NSUInteger
pub fn testCaseCount(&self) -> NSUInteger
Number of test cases. Must be overridden by subclasses.
Sourcepub fn testRunClass(&self) -> Option<&'static AnyClass>
pub fn testRunClass(&self) -> Option<&'static AnyClass>
The XCTestRun subclass that will be instantiated when the test is run to hold the test’s results. Must be overridden by subclasses.
Sourcepub fn testRun(&self) -> Option<Retained<XCTestRun>>
pub fn testRun(&self) -> Option<Retained<XCTestRun>>
The test run object that executed the test, an instance of testRunClass. If the test has not yet been run, this will be nil.
Sourcepub fn performTest(&self, run: &XCTestRun)
pub fn performTest(&self, run: &XCTestRun)
The method through which tests are executed. Must be overridden by subclasses.
Sourcepub fn runTest(&self)
pub fn runTest(&self)
Creates an instance of the testRunClass and passes it as a parameter to -performTest:.
Sourcepub fn setUpWithCompletionHandler(
&self,
completion: &DynBlock<dyn Fn(*mut NSError)>,
)
Available on crate feature block2 only.
pub fn setUpWithCompletionHandler( &self, completion: &DynBlock<dyn Fn(*mut NSError)>, )
block2 only.Asynchronous set up method called before the invocation of each test method in the class.
This method is called before invoking setUpWithError, setUp, and the test method.
Parameter completion: A block which must be called to signal completion of set up.
May be called asynchronously. If the block’s error argument is non-nil, the specified error
is recorded as a thrown error issue.
Sourcepub fn setUpWithError(&self) -> Result<(), Retained<NSError>>
pub fn setUpWithError(&self) -> Result<(), Retained<NSError>>
This method is called before invoking setUp and the test method.
Sourcepub fn setUp(&self)
pub fn setUp(&self)
Setup method called before the invocation of each test method in the class.
Sourcepub fn tearDown(&self)
pub fn tearDown(&self)
Teardown method called after the invocation of each test method in the class.
Sourcepub fn tearDownWithError(&self) -> Result<(), Retained<NSError>>
pub fn tearDownWithError(&self) -> Result<(), Retained<NSError>>
This method is called after invoking the test method (if applicable) and
tearDown.
Sourcepub fn tearDownWithCompletionHandler(
&self,
completion: &DynBlock<dyn Fn(*mut NSError)>,
)
Available on crate feature block2 only.
pub fn tearDownWithCompletionHandler( &self, completion: &DynBlock<dyn Fn(*mut NSError)>, )
block2 only.Asynchronous tear down method called after invoking the test method.
This method is called after invoking the test method (if applicable), tearDown, and
tearDownWithError.
Parameter completion: A block which must be called to signal completion of tear down.
May be called asynchronously. If the block’s error argument is non-nil, the specified error
is recorded as a thrown error issue.
Methods from Deref<Target = NSObject>§
Sourcepub fn doesNotRecognizeSelector(&self, sel: Sel) -> !
pub fn doesNotRecognizeSelector(&self, sel: Sel) -> !
Handle messages the object doesn’t recognize.
See Apple’s documentation for details.
Methods from Deref<Target = AnyObject>§
Sourcepub fn class(&self) -> &'static AnyClass
pub fn class(&self) -> &'static AnyClass
Dynamically find the class of this object.
§Panics
May panic if the object is invalid (which may be the case for objects
returned from unavailable init/new methods).
§Example
Check that an instance of NSObject has the precise class NSObject.
use objc2::ClassType;
use objc2::runtime::NSObject;
let obj = NSObject::new();
assert_eq!(obj.class(), NSObject::class());Sourcepub unsafe fn get_ivar<T>(&self, name: &str) -> &Twhere
T: Encode,
👎Deprecated: this is difficult to use correctly, use Ivar::load instead.
pub unsafe fn get_ivar<T>(&self, name: &str) -> &Twhere
T: Encode,
Ivar::load instead.Use Ivar::load instead.
§Safety
The object must have an instance variable with the given name, and it
must be of type T.
See Ivar::load_ptr for details surrounding this.
Sourcepub fn downcast_ref<T>(&self) -> Option<&T>where
T: DowncastTarget,
pub fn downcast_ref<T>(&self) -> Option<&T>where
T: DowncastTarget,
Attempt to downcast the object to a class of type T.
This is the reference-variant. Use Retained::downcast if you want
to convert a retained object to another type.
§Mutable classes
Some classes have immutable and mutable variants, such as NSString
and NSMutableString.
When some Objective-C API signature says it gives you an immutable class, it generally expects you to not mutate that, even though it may technically be mutable “under the hood”.
So using this method to convert a NSString to a NSMutableString,
while not unsound, is generally frowned upon unless you created the
string yourself, or the API explicitly documents the string to be
mutable.
See Apple’s documentation on mutability and on
isKindOfClass: for more details.
§Generic classes
Objective-C generics are called “lightweight generics”, and that’s because they aren’t exposed in the runtime. This makes it impossible to safely downcast to generic collections, so this is disallowed by this method.
You can, however, safely downcast to generic collections where all the
type-parameters are AnyObject.
§Panics
This works internally by calling isKindOfClass:. That means that the
object must have the instance method of that name, and an exception
will be thrown (if CoreFoundation is linked) or the process will abort
if that is not the case. In the vast majority of cases, you don’t need
to worry about this, since both root objects NSObject and
NSProxy implement this method.
§Examples
Cast an NSString back and forth from NSObject.
use objc2::rc::Retained;
use objc2_foundation::{NSObject, NSString};
let obj: Retained<NSObject> = NSString::new().into_super();
let string = obj.downcast_ref::<NSString>().unwrap();
// Or with `downcast`, if we do not need the object afterwards
let string = obj.downcast::<NSString>().unwrap();Try (and fail) to cast an NSObject to an NSString.
use objc2_foundation::{NSObject, NSString};
let obj = NSObject::new();
assert!(obj.downcast_ref::<NSString>().is_none());Try to cast to an array of strings.
use objc2_foundation::{NSArray, NSObject, NSString};
let arr = NSArray::from_retained_slice(&[NSObject::new()]);
// This is invalid and doesn't type check.
let arr = arr.downcast_ref::<NSArray<NSString>>();This fails to compile, since it would require enumerating over the array to ensure that each element is of the desired type, which is a performance pitfall.
Downcast when processing each element instead.
use objc2_foundation::{NSArray, NSObject, NSString};
let arr = NSArray::from_retained_slice(&[NSObject::new()]);
for elem in arr {
if let Some(data) = elem.downcast_ref::<NSString>() {
// handle `data`
}
}Trait Implementations§
Source§impl AsRef<AnyObject> for XCTestCase
impl AsRef<AnyObject> for XCTestCase
Source§impl AsRef<NSObject> for XCTestCase
impl AsRef<NSObject> for XCTestCase
Source§impl AsRef<XCTest> for XCTestCase
impl AsRef<XCTest> for XCTestCase
Source§impl AsRef<XCTestCase> for XCTestCase
impl AsRef<XCTestCase> for XCTestCase
Source§impl Borrow<AnyObject> for XCTestCase
impl Borrow<AnyObject> for XCTestCase
Source§impl Borrow<NSObject> for XCTestCase
impl Borrow<NSObject> for XCTestCase
Source§impl Borrow<XCTest> for XCTestCase
impl Borrow<XCTest> for XCTestCase
Source§impl ClassType for XCTestCase
impl ClassType for XCTestCase
Source§const NAME: &'static str = "XCTestCase"
const NAME: &'static str = "XCTestCase"
Source§type ThreadKind = <<XCTestCase as ClassType>::Super as ClassType>::ThreadKind
type ThreadKind = <<XCTestCase as ClassType>::Super as ClassType>::ThreadKind
Source§impl Debug for XCTestCase
impl Debug for XCTestCase
Source§impl DefaultRetained for XCTestCase
impl DefaultRetained for XCTestCase
Source§impl Deref for XCTestCase
impl Deref for XCTestCase
Source§impl Hash for XCTestCase
impl Hash for XCTestCase
Source§impl Message for XCTestCase
impl Message for XCTestCase
Source§impl NSObjectProtocol for XCTestCase
impl NSObjectProtocol for XCTestCase
Source§fn isEqual(&self, other: Option<&AnyObject>) -> bool
fn isEqual(&self, other: Option<&AnyObject>) -> bool
Source§fn hash(&self) -> usize
fn hash(&self) -> usize
Source§fn isKindOfClass(&self, cls: &AnyClass) -> bool
fn isKindOfClass(&self, cls: &AnyClass) -> bool
Source§fn is_kind_of<T>(&self) -> bool
fn is_kind_of<T>(&self) -> bool
isKindOfClass directly, or cast your objects with AnyObject::downcast_ref