Unit Testing & MockK Interview Questions

TESTING › Unit

What makes a good unit test?

What a strong answer covers: It tests one behaviour through the public API, is fast, deterministic and independent of other tests, reads clearly (arrange, act, assert or given-when-then), has a descriptive name, and fails for one reason. It tests behaviour rather than implementation details, so refactoring doesn't break it.

What is the difference between a mock, a stub, a fake and a spy?

What a strong answer covers: A stub returns canned answers; a mock also verifies that certain calls were made; a fake is a lightweight working implementation, like an in-memory repository; a spy wraps a real object and records calls while running real code. Google's guidance prefers fakes for your own interfaces because they make tests less brittle.

What do you actually test in a ViewModel, and how?

What a strong answer covers: Given inputs and fake dependencies, check the state it exposes and the effects it triggers: initial state, loading then success, error handling, how user events change state, and that it calls the repository correctly. Use runTest with a test dispatcher replacing Dispatchers.Main (a MainDispatcherRule), fakes for repositories, and collect state with Turbine or check value after advanceUntilIdle.

When do mocks make tests worse, and why do many teams prefer fakes?

What a strong answer covers: Heavy mocking ties tests to implementation: verifying exact call sequences breaks tests whenever you refactor, even when behaviour is correct; mocks can return values the real thing never would; and stubbing every call makes tests long and unclear. Fakes behave like the real implementation, are reusable across tests, and let you assert on outcomes. Mocks are still useful for third-party types or verifying an important interaction like an analytics call.

How do you test code that depends on time, randomness or Android framework classes, without Robolectric everywhere?

What a strong answer covers: Inject the dependency instead of calling it directly: a Clock or time provider for time, a seeded Random or an id generator interface, and wrappers for framework things like resources, connectivity or location. Keep business logic in plain Kotlin classes that don't touch Android, so they run as fast JVM tests. Use Robolectric or instrumented tests only for code that genuinely integrates with the framework.

Back to Unit Testing & MockK