Unit test a ViewModel with a mocked NetworkService
dependency injection and test isolation.
inject the protocol, supply a mock returning canned data, assert published state transitions.
hitting the real network or testing the concrete service instead of the ViewModel.
WHAT THIS TESTS This probes whether you understand testable architecture: depending on abstractions rather than concrete types so you can substitute behaviour in tests. The interviewer wants protocol-oriented dependency injection, not singletons reached for inside the ViewModel.
A GOOD ANSWER COVERS The ViewModel should accept the NetworkService protocol through its initializer, defaulting to the real implementation in production. In the test you create a mock type conforming to the same protocol whose fetch method returns a predetermined success value, perhaps with a configurable stubbed result. You instantiate the ViewModel with that mock, invoke the action, and assert the observable state. If the ViewModel publishes via Combine, ObservableObject, or async sequences, you assert the loading flag flips on then off and the data property holds the expected decoded model.
COMMON WRONG ANSWERS Using URLProtocol stubbing when simple protocol mocking suffices, calling the real network and tolerating slowness, or constructing the concrete NetworkService inside the ViewModel which makes substitution impossible. Another mistake is asserting the mock was configured rather than verifying the ViewModel produced correct state.
LIKELY FOLLOW-UPS How would you test the failure path? How do you handle the async gap between calling fetch and the state updating? How would you verify the network method was called exactly once with the right arguments?
ONE CONCRETE EXAMPLE Define protocol NetworkServicing with func fetchUsers async throws returning Users. The production AppNetworkService conforms to it. In tests, MockNetworkService stores a stubbedUsers array and a callCount; its fetchUsers increments the count and returns the stub. The test creates ViewModel with the mock, awaits viewModel.loadUsers, then asserts viewModel.users equals the stub, viewModel.isLoading is false, and mock.callCount equals one. No real connection is opened, so the test is fast and deterministic.
Read the original → donnywals.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.