XCTestCase

Struct XCTestCase 

Source
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

Source

pub unsafe fn testCaseWithInvocation( invocation: Option<&NSInvocation>, ) -> Retained<Self>

Source

pub unsafe fn initWithInvocation( this: Allocated<Self>, invocation: Option<&NSInvocation>, ) -> Retained<Self>

Source

pub unsafe fn testCaseWithSelector(selector: Sel) -> Option<Retained<Self>>

§Safety

selector must be a valid selector.

Source

pub unsafe fn initWithSelector( this: Allocated<Self>, selector: Sel, ) -> Retained<Self>

§Safety

selector must be a valid selector.

Source

pub unsafe fn invocation(&self) -> Option<Retained<NSInvocation>>

The invocation used when this test is run.

Source

pub unsafe fn setInvocation(&self, invocation: Option<&NSInvocation>)

Setter for invocation.

Source

pub fn invokeTest(&self)

Invoking a test performs its setUp, invocation, and tearDown. In general this should not be called directly.

Source

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.

Source

pub fn setContinueAfterFailure(&self, continue_after_failure: bool)

Source

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.

Source

pub fn testInvocations() -> Retained<NSArray<NSInvocation>>

Invocations for each test method in the test case.

Source

pub fn addTeardownBlock(&self, block: &DynBlock<dyn Fn()>)

Available on crate feature 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.

Source

pub unsafe fn addAsyncTeardownBlock( &self, block: &DynBlock<dyn Fn(NonNull<DynBlock<dyn Fn(*mut NSError)>>)>, )

Available on crate feature 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.

Source

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.

Source

pub fn setExecutionTimeAllowance( &self, execution_time_allowance: NSTimeInterval, )

Source§

impl XCTestCase

Methods declared on superclass NSObject.

Source

pub fn init(this: Allocated<Self>) -> Retained<Self>

Source

pub fn new() -> Retained<Self>

Source§

impl XCTestCase

XCTestSuiteExtensions.

Source

pub fn defaultTestSuite() -> Retained<XCTestSuite>

Returns a test suite containing test cases for all of the tests in the class.

Source

pub fn setUp()

Suite-level setup method called before the class begins to run any of its test methods or their associated per-instance setUp methods.

Source

pub fn tearDown()

Suite-level teardown method called after the class has finished running all of its test methods and their associated per-instance tearDown methods and teardown blocks.

Source§

impl XCTestCase

This impl block contains no items.

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.

Interface extension for measure related API.

Source

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:

Source

pub fn measureBlock(&self, block: &DynBlock<dyn Fn() + '_>)

Available on crate feature 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.

Source

pub fn measureMetrics_automaticallyStartMeasuring_forBlock( &self, metrics: &NSArray<XCTPerformanceMetric>, automatically_start_measuring: bool, block: &DynBlock<dyn Fn() + '_>, )

Available on crate feature 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.

Source

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.

Source

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.

Source

pub fn defaultMetrics() -> Retained<NSArray<ProtocolObject<dyn XCTMetric>>>

A collection of metrics to be taken by default when -measureBlock or -measureWithOptions:block: is called.

Source

pub fn defaultMeasureOptions() -> Retained<XCTMeasureOptions>

Collection of configurable settings to change how measurements are taken.

Source

pub fn measureWithMetrics_block( &self, metrics: &NSArray<ProtocolObject<dyn XCTMetric>>, block: &DynBlock<dyn Fn() + '_>, )

Available on crate feature 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.

Source

pub fn measureWithOptions_block( &self, options: &XCTMeasureOptions, block: &DynBlock<dyn Fn() + '_>, )

Available on crate feature 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

Source

pub fn measureWithMetrics_options_block( &self, metrics: &NSArray<ProtocolObject<dyn XCTMetric>>, options: &XCTMeasureOptions, block: &DynBlock<dyn Fn() + '_>, )

Available on crate feature 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.

Source

pub fn recordFailureWithDescription_inFile_atLine_expected( &self, description: &NSString, file_path: &NSString, line_number: NSUInteger, expected: bool, )

👎Deprecated

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.

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.

Source

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.

Source

pub unsafe fn waitForExpectationsWithTimeout_handler( &self, timeout: NSTimeInterval, handler: XCWaitCompletionHandler, mtm: MainThreadMarker, )

Available on crate feature 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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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_observe should be of the correct type.
  • expected_value should be of the correct type.
Source

pub unsafe fn keyValueObservingExpectationForObject_keyPath_handler( &self, object_to_observe: &AnyObject, key_path: &NSString, handler: XCKeyValueObservingExpectationHandler, ) -> Retained<XCTestExpectation>

Available on crate feature 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_observe should be of the correct type.
  • handler must be a valid pointer or null.
Source

pub unsafe fn expectationForNotification_object_handler( &self, notification_name: &NSNotificationName, object_to_observe: Option<&AnyObject>, handler: XCNotificationExpectationHandler, ) -> Retained<XCTestExpectation>

Available on crate feature 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_observe should be of the correct type.
  • handler must be a valid pointer or null.
Source

pub 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.

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_observe should be of the correct type.
  • handler must be a valid pointer or null.
Source

pub unsafe fn expectationForPredicate_evaluatedWithObject_handler( &self, predicate: &NSPredicate, object: Option<&AnyObject>, handler: XCPredicateExpectationHandler, ) -> Retained<XCTestExpectation>

Available on crate feature 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
  • object should be of the correct type.
  • handler must be a valid pointer or null.
Source§

impl XCTestCase

XCUIApplication_LaunchTesting.

Source

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.

Source

pub 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.

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.

Source

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

Source

pub fn testCaseCount(&self) -> NSUInteger

Number of test cases. Must be overridden by subclasses.

Source

pub fn name(&self) -> Retained<NSString>

Test’s name. Must be overridden by subclasses.

Source

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.

Source

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.

Source

pub fn performTest(&self, run: &XCTestRun)

The method through which tests are executed. Must be overridden by subclasses.

Source

pub fn runTest(&self)

Creates an instance of the testRunClass and passes it as a parameter to -performTest:.

Source

pub fn setUpWithCompletionHandler( &self, completion: &DynBlock<dyn Fn(*mut NSError)>, )

Available on crate feature 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.

Source

pub fn setUpWithError(&self) -> Result<(), Retained<NSError>>

This method is called before invoking setUp and the test method.

Source

pub fn setUp(&self)

Setup method called before the invocation of each test method in the class.

Source

pub fn tearDown(&self)

Teardown method called after the invocation of each test method in the class.

Source

pub fn tearDownWithError(&self) -> Result<(), Retained<NSError>>

This method is called after invoking the test method (if applicable) and tearDown.

Source

pub fn tearDownWithCompletionHandler( &self, completion: &DynBlock<dyn Fn(*mut NSError)>, )

Available on crate feature 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>§

Source

pub fn doesNotRecognizeSelector(&self, sel: Sel) -> !

Handle messages the object doesn’t recognize.

See Apple’s documentation for details.

Methods from Deref<Target = AnyObject>§

Source

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());
Source

pub unsafe fn get_ivar<T>(&self, name: &str) -> &T
where T: Encode,

👎Deprecated: this is difficult to use correctly, use 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.

Source

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

Source§

fn as_ref(&self) -> &AnyObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<NSObject> for XCTestCase

Source§

fn as_ref(&self) -> &NSObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<XCTest> for XCTestCase

Source§

fn as_ref(&self) -> &XCTest

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<XCTestCase> for XCTestCase

Source§

fn as_ref(&self) -> &Self

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Borrow<AnyObject> for XCTestCase

Source§

fn borrow(&self) -> &AnyObject

Immutably borrows from an owned value. Read more
Source§

impl Borrow<NSObject> for XCTestCase

Source§

fn borrow(&self) -> &NSObject

Immutably borrows from an owned value. Read more
Source§

impl Borrow<XCTest> for XCTestCase

Source§

fn borrow(&self) -> &XCTest

Immutably borrows from an owned value. Read more
Source§

impl ClassType for XCTestCase

Source§

const NAME: &'static str = "XCTestCase"

The name of the Objective-C class that this type represents. Read more
Source§

type Super = XCTest

The superclass of this class. Read more
Source§

type ThreadKind = <<XCTestCase as ClassType>::Super as ClassType>::ThreadKind

Whether the type can be used from any thread, or from only the main thread. Read more
Source§

fn class() -> &'static AnyClass

Get a reference to the Objective-C class that this type represents. Read more
Source§

fn as_super(&self) -> &Self::Super

Get an immutable reference to the superclass.
Source§

impl Debug for XCTestCase

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl DefaultRetained for XCTestCase

Source§

fn default_retained() -> Retained<Self>

The default Retained for a type. Read more
Source§

impl Deref for XCTestCase

Source§

type Target = XCTest

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl Hash for XCTestCase

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Message for XCTestCase

Source§

fn retain(&self) -> Retained<Self>
where Self: Sized,

Increment the reference count of the receiver. Read more
Source§

impl NSObjectProtocol for XCTestCase

Source§

fn isEqual(&self, other: Option<&AnyObject>) -> bool
where Self: Sized + Message,

Check whether the object is equal to an arbitrary other object. Read more
Source§

fn hash(&self) -> usize
where Self: Sized + Message,

An integer that can be used as a table address in a hash table structure. Read more
Source§

fn isKindOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of the class, or one of its subclasses. Read more
Source§

fn is_kind_of<T>(&self) -> bool
where T: ClassType, Self: Sized + Message,

👎Deprecated: use isKindOfClass directly, or cast your objects with AnyObject::downcast_ref
Check if the object is an instance of the class type, or one of its subclasses. Read more
Source§

fn isMemberOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of a specific class, without checking subclasses. Read more
Source§

fn respondsToSelector(&self, aSelector: Sel) -> bool
where Self: Sized + Message,

Check whether the object implements or inherits a method with the given selector. Read more
Source§

fn conformsToProtocol(&self, aProtocol: &AnyProtocol) -> bool
where Self: Sized + Message,

Check whether the object conforms to a given protocol. Read more
Source§

fn description(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object. Read more
Source§

fn debugDescription(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object to use when debugging. Read more
Source§

fn isProxy(&self) -> bool
where Self: Sized + Message,

Check whether the receiver is a subclass of the NSProxy root class instead of the usual NSObject. Read more
Source§

fn retainCount(&self) -> usize
where Self: Sized + Message,

The reference count of the object. Read more
Source§

impl PartialEq for XCTestCase

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl RefEncode for XCTestCase

Source§

const ENCODING_REF: Encoding = <XCTest as ::objc2::RefEncode>::ENCODING_REF

The Objective-C type-encoding for a reference of this type. Read more
Source§

impl XCTActivity for XCTestCase

Source§

fn name(&self) -> Retained<NSString>
where Self: Sized + Message,

Human-readable name of the activity, given at creation time.
Source§

fn addAttachment(&self, attachment: &XCTAttachment)
where Self: Sized + Message,

Adds an attachment which is always kept by Xcode, regardless of the test result. Thread-safe, attachments can be added from any thread, are reported in the order they are added.
Source§

impl XCTWaiterDelegate for XCTestCase

Source§

fn waiter_didTimeoutWithUnfulfilledExpectations( &self, waiter: &XCTWaiter, unfulfilled_expectations: &NSArray<XCTestExpectation>, )
where Self: Sized + Message,

Invoked when not all waited on expectations are fulfilled during the timeout period. If the delegate is an XCTestCase instance, this will be reported as a test failure.
Source§

fn waiter_fulfillmentDidViolateOrderingConstraintsForExpectation_requiredExpectation( &self, waiter: &XCTWaiter, expectation: &XCTestExpectation, required_expectation: &XCTestExpectation, )
where Self: Sized + Message,

Invoked when the -wait call has specified that fulfillment order should be enforced and an expectation has been fulfilled in the wrong order. If the delegate is an XCTestCase instance, this will be reported as a test failure.
Source§

fn waiter_didFulfillInvertedExpectation( &self, waiter: &XCTWaiter, expectation: &XCTestExpectation, )
where Self: Sized + Message,

Invoked when an expectation marked as inverted (/see inverted) is fulfilled. If the delegate is an XCTestCase instance, this will be reported as a test failure.
Source§

fn nestedWaiter_wasInterruptedByTimedOutWaiter( &self, waiter: &XCTWaiter, outer_waiter: &XCTWaiter, )
where Self: Sized + Message,

Invoked when the waiter is interrupted prior to its expectations being fulfilled or timing out. This occurs when an “outer” waiter times out, resulting in any waiters nested inside it being interrupted to allow the call stack to quickly unwind.
Source§

impl DowncastTarget for XCTestCase

Source§

impl Eq for XCTestCase

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T> AnyThread for T
where T: ClassType<ThreadKind = dyn AnyThread + 'a> + ?Sized,

Source§

fn alloc() -> Allocated<Self>
where Self: Sized + ClassType,

Allocate a new instance of the class. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> AutoreleaseSafe for T
where T: ?Sized,