Testen in Swift: Unit, Integration, E2E von A bis Z

Online Python-Trainer für Anfänger

Lernen Sie Python einfach ohne theoretische Überlastung. Lösen Sie praktische Aufgaben mit automatischer Überprüfung und schreiben Sie Code direkt im Browser.

Kurs starten
ctation(description: "User saved") userService.fetchAndSaveUser(id: 1) { success in XCTAssertTrue(success) let user = try? self.coreDataStack.viewContext.existingObject(with: 1) XCTAssertNotNil(user, "User should be saved in database") expectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } }

Key Principles for Integration Testing

  • Real but isolated: use in-memory databases or test servers.
  • Speed matters: avoid network calls if possible — mock only external APIs, test internal integration with real objects.
  • Teardown: always clean up test data after each test to avoid side effects.


Level 3: E2E Testing — Full System Validation

End-to-end (E2E) tests simulate real user scenarios: launching the app, tapping buttons, waiting for responses, checking UI changes. On Apple platforms, the main tool is XCTest with XCUIApplication for UI automation.



Writing an E2E Test

Create a new UI Test Target (File → New → Target → UI Testing Bundle). Example:

import XCTest

class LoginFlowE2ETests: XCTestCase { var app: XCUIApplication! override func setUp() { app = XCUIApplication() app.launch() } func testSuccessfulLogin() { let usernameField = app.textFields["username"] XCTAssertTrue(usernameField.exists) usernameField.tap() usernameField.typeText("testuser") let passwordField = app.secureTextFields["password"] XCTAssertTrue(passwordField.exists) passwordField.tap() passwordField.typeText("password123") app.buttons["login"].tap() let welcomeLabel = app.staticTexts["Welcome, testuser!"] XCTAssertTrue(welcomeLabel.waitForExistence(timeout: 5)) } }


Best Practices for E2E Testing

  • Stability: add explicit waits (waitForExistence), avoid hard-coded delays.
  • Test data: create dedicated test accounts or use mocks for network responses.
  • Run on real devices: simulator can differ from real hardware (keyboard, gestures).
  • Not too many: 5-10 key user flows are enough; E2E tests are slow and flaky.


Final Tips: How to Organize Testing in Your Project

  • Structure by feature: group tests by module/feature, not by type. Example: Tests/Auth/, Tests/Profile/.
  • Continuous Integration: run tests on every push using GitHub Actions, Swift, or Xcode Cloud.
  • Parallel execution: use Xcode Test Plan to run tests in parallel.
  • Prioritize: unit tests → fast feedback, integration tests → key interactions, E2E → critical paths.

Testing in Swift is not just about checking code. It's about confidence. Confidence that your app won't crash after an update, that the payment goes through, that the data is saved correctly. Invest in tests — and your users will thank you.



Blogs

Buchempfehlungen