tezvyn:

Unit test a ViewModel with a mocked NetworkService

Source: interviewintermediate

WHAT IT TESTS: dependency injection and test isolation. OUTLINE: inject the protocol, supply a mock returning canned data, assert published state transitions. RED FLAG: hitting the real network or testing the concrete service instead of the ViewModel.

WHAT IT TESTS: whether you isolate units via protocol-based dependency injection. ANSWER OUTLINE: the ViewModel takes NetworkService as an init parameter; in the test you pass a MockNetworkService conforming to that protocol that returns a stubbed success result; you trigger the fetch and assert the ViewModel's published or observable state moves from loading to loaded with the expected model. RED FLAG: making a real URLSession call, depending on live servers, or asserting on the mock rather than the ViewModel's resulting state.

Read the original → interview

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.

Unit test a ViewModel with a mocked NetworkService · Tezvyn