We’ve an app constructed with SwiftUI, utilizing MVVM structure, and we wish to implement unit testing on the view stage. So, to provide an instance, that is how a view would seem like:
struct RandomView<InjectedModel>: View the place InjectedModel: InjectedModelViewModelProtocol {
@StateObject var viewModel: InjectedModel
init(
viewModel: @autoclosure @escaping () -> InjectedModel
) {
self._viewModel = StateObject(wrappedValue: viewModel())
}
And a view mannequin protocol could be represented by an interface akin to:
protocol InjectedModelViewModelProtocol: ObservableObject {
var someProperty: String { get set }
func someMethod()
}
The rationale for doing that is that we wish to mock the view mannequin and check the view to see the correct values / parts within the fields and so forth (for reference, we are going to nonetheless use the XCUIElement
and the remainder of the APIs out there in commonplace UI testing).
This works thus far and it permits for the view mannequin to be mocked when working the checks. However now, the questions: is it okay for the views to have the view fashions injected on this method, regarding the efficiency and different SwiftUI behaviours? We’re planning to have each small view constructed like this. And I do know Apple mentions in one in every of its WWDC speak to not have actually something to evolve to protocols. Additionally, undecided how good this fashion of working with view mannequin’s properties is, and if we cannot hit any limitations or different issues.
I’ve tried this resolution and works for small iteration, however was questioning from a perspective of long run improvement.