Refactoring & Testing Legacy Code

The Problem

The Solution

Requirements

Initial view controller
Folder Structure
Application
Create ViewModels Folders
Choose New File
Create MainViewModel.swift
Folder Structure with ViewModels Folder

Dependency Injection!

MainViewModel.swift
LocationService.swift
ApiClient.swift
private var viewModel: MainViewModel!
viewModel = MainViewModel(locationServiceType: LocationService.shared, apiClientType: ApiClient.shared, addressCompletion: { address in
self.addressLabel.text = address
})
viewModel.updateCurrentAddress { [unowned self] (address) in
self.addressLabel.text = address
}
Simulate Location

Testing the View Model

MainViewModelTests.swift
Creating ServiceStub.swift
ServiceStub.swift

Conclusion

Follow me

iOS Engineer