Developing Unit tests for an iOS application (XCTest)

NOVASOLUTIONS.TECHNOLOGY is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.
Development and support of all types of mobile applications:
Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1 servicesAll 1735 services
Developing Unit tests for an iOS application (XCTest)
Medium
~3-5 business days
FAQ
Our competencies:
Development stages
Latest works
  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    756
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    624
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1050
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    947
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    862
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    445

Unit Test Development for iOS Application (XCTest)

Typical situation: ViewModel grows to 500 lines, mixes business logic, data formatting and direct network calls. Add new feature — something breaks in old flow. Revert — works again, but reason unclear. Unit tests on XCTest — not about "coverage for coverage," but about ability to refactor fearlessly.

What to Test and How

Business logic — main priority. ViewModel, Interactor, UseCase — everything with if/switch branches, calculations, data transformations. Protocol-oriented approach Swift makes this convenient: dependencies injected via protocols, in tests substituted with mocks.

// Service protocol
protocol UserServiceProtocol {
    func fetchUser(id: String) async throws -> User
}

// Mock for tests
class MockUserService: UserServiceProtocol {
    var stubbedUser: User?
    var stubbedError: Error?

    func fetchUser(id: String) async throws -> User {
        if let error = stubbedError { throw error }
        return stubbedUser!
    }
}

// Test
func testFetchUserSuccess() async throws {
    let mockService = MockUserService()
    mockService.stubbedUser = User(id: "1", name: "Test")
    let sut = UserViewModel(service: mockService)

    await sut.loadUser(id: "1")

    XCTAssertEqual(sut.user?.name, "Test")
    XCTAssertFalse(sut.isLoading)
}

Asynchronous code — second by importance. Modern Swift with async/await tests natively: XCTest supports async test functions with iOS 15+ and Xcode 13+. For Combine-based code — XCTestExpectation + sink.

Edge cases — what really crashes in production: empty array, nil value, string with Unicode, date in different timezone. Not "happy path," but exact edge cases.

Architecture Convenient for Testing

XCTest tests write simply when architecture assumes dependency inversion. MVVM with DI through initializer, Clean Architecture with UseCase — test directly. Singletons and static methods — no. If project doesn't use DI, part of work — refactoring before writing tests.

Common problem: ViewModel calls UserDefaults directly, Date() directly. Both need wrapping in protocols and injecting — otherwise tests depend on system state and startup time.

Testing Combine and async/await

// Combine: test Publisher
func testPublisherEmitsValue() {
    let expectation = expectation(description: "Value received")
    var cancellables = Set<AnyCancellable>()

    sut.statePublisher
        .dropFirst()  // skip initial state
        .sink { state in
            XCTAssertEqual(state, .loaded)
            expectation.fulfill()
        }
        .store(in: &cancellables)

    sut.loadData()
    waitForExpectations(timeout: 2)
}

CI Integration

Run tests on each PR via xcodebuild test -scheme MyApp -destination 'platform=iOS Simulator,name=iPhone 15'. Matrix of iOS versions fixed in GitHub Actions / Bitrise configuration. Code coverage report via Xcode Coverage Report or xcov gem. Coverage goal — not 100%, but logic: ViewModel/Interactor/UseCase should be 80%+ covered, UI — don't touch with unit tests.

Typical iOS Unit Test Errors

  • @testable import without -enable-testing flag in build settings — import doesn't work in CI
  • Tests dependent on orderXCTest doesn't guarantee execution order, each test isolated via setUp()/tearDown()
  • Real network requests in tests — test becomes unstable and slow. Always mock via URLProtocol subclass or URLSession with custom URLSessionConfiguration

Process of Work

Code audit → isolate testable components → if needed minimal refactoring for DI → write tests → CI integration. Coverage report after completion.

Timeframe: 3–5 days depending on codebase volume and current level of architectural component isolation.