> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/appendix/testing-system/xctest.md).

# XCTest

default testing framework, bundled with the Xcode IDE.

{% tabs %}
{% tab title="📙 書籍" %}

* Test-Driven Development in Swift (2021)
  {% endtab %}

{% tab title="📘 手冊" %}

* help
  {% endtab %}
  {% endtabs %}

{% tabs %}
{% tab title="code" %}
{% hint style="info" %}
XCTestCase offers methods to run code before each test or all the tests will run, as well as after each test or all the tests did run:
{% endhint %}

```swift
import XCTest
@testable import MyProject

// ⭐️ make a subclass of XCTestCase
class TestsForMyType: XCTestCase {

    /* -------- test case life cycle -------- */
    
    // ⭐️ runs before ALL tests
    override class func setUp() { ... }
    
    // ⭐️ runs after all tests
    override class func tearDown() { ... }
    
    // ⭐️ runs before each test
    override func setUpWithError() throws { ... }

    // ⭐️ runs after each test
    override func tearDownWithError() throws { ... }

    /* -------- test cases -------- */
 
    // ⭐️ method name starting with “test”
    func testThis() { } 
    func testThat() { } 

    // ⭐️ performance test case name starting with “testPerformance”?
    func testPerformanceExample() throws {
        self.measure {
            // code to measure the time of
        }
    }
}
```

{% endtab %}

{% tab title="Bool" %}

* XCTAssertTrue(true)&#x20;
* XCTAssertFalse(false)
  {% endtab %}

{% tab title="Compare" %}
{% hint style="info" %}
compare the values of types conforming to <mark style="color:red;">**Comparable**</mark>:
{% endhint %}

* XCTAssertLessThan(1, 2)&#x20;
* XCTAssertGreaterThan(2, 1)&#x20;
* XCTAssertLessThanOrEqual(2, 2)&#x20;
* XCTAssertGreaterThanOrEqual(2, 1)
  {% endtab %}

{% tab title="Nil" %}

* XCTAssertNil(nil)&#x20;
* XCTAssertNotNil("this is not nil")

```swift
// will fail if user == nil, or firstName !== "John"
XCTAssertEqual(user?.firstName, "John")

// use `XCTUnwrap` instead
let u = try XCTUnwrap(user)            // fail if user == nil
XCTAssertEqual(u.firstName, "John")    // fail if not equal

```

{% endtab %}

{% tab title="Throws" %}

* XCTAssertThrowsError(try aFunctionThatThrows())&#x20;
* XCTAssertNoThrow(try aFunctionThatThrows())
  {% endtab %}
  {% endtabs %}
