What are mocking and stubbing techniques for UIKit in Swift?

Mocking and stubbing techniques are essential for unit testing in UIKit applications built with Swift. These techniques help simulate objects and the behavior of dependencies, allowing developers to verify the functionality of their code without relying on specific implementations or external systems.
mocking, stubbing, unit testing, UIKit, Swift, dependency injection, test-driven development (TDD)

        // Example of mocking and stubbing in Swift with XCTest framework
        import XCTest
        import UIKit

        // Protocol to define the behavior of a network service
        protocol NetworkService {
            func fetchData() -> String
        }

        // Mock class to simulate the NetworkService
        class MockNetworkService: NetworkService {
            func fetchData() -> String {
                return "Mocked Data"
            }
        }

        class MyViewController: UIViewController {
            var networkService: NetworkService?

            func displayData() -> String {
                return networkService?.fetchData() ?? "No Data"
            }
        }

        class MyViewControllerTests: XCTestCase {
            func testDisplayData() {
                // Arrange
                let mockService = MockNetworkService()
                let viewController = MyViewController()
                viewController.networkService = mockService

                // Act
                let result = viewController.displayData()

                // Assert
                XCTAssertEqual(result, "Mocked Data")
            }
        }
    

mocking stubbing unit testing UIKit Swift dependency injection test-driven development (TDD)