Android Development Android Testing 2 — Questions and Answers
Question 1: Which Espresso method is used to find a view by its resource ID?
- onView(withId()) (Correct answer)
- findView(byId())
- getView(withId())
- selectView(byId())
Correct answer: onView(withId())
onView(withId(R.id.viewId)) finds the view with the specified resource ID in Espresso UI tests.
Question 2: What is Robolectric used for in Android testing?
- Running Android instrumentation tests on the JVM without a device or emulator (Correct answer)
- Mocking API responses
- Testing animations
- Performance testing
Correct answer: Running Android instrumentation tests on the JVM without a device or emulator
Robolectric simulates the Android framework on the JVM, allowing instrumentation-style tests to run locally without needing a device.
Question 3: What does the @Before annotation do in JUnit?
- Marks a method to run before each test method in the class (Correct answer)
- Runs code before the test class loads
- Indicates a precondition assertion
- Marks a setup method that runs once
Correct answer: Marks a method to run before each test method in the class
@Before marks a method that JUnit executes before each @Test method, commonly used for test setup like initializing objects.
Question 4: Which Espresso method simulates a button click in a UI test?
- perform(click()) (Correct answer)
- doClick()
- tapView()
- simulate(click())
Correct answer: perform(click())
In Espresso, perform(click()) is chained after onView() to simulate a user tapping on the matched view.
Question 5: What is the TestCoroutineDispatcher used for in Android testing?
- To control coroutine execution timing in tests for deterministic behavior (Correct answer)
- To dispatch test events to coroutines
- To run UI tests asynchronously
- To mock network dispatchers
Correct answer: To control coroutine execution timing in tests for deterministic behavior
TestCoroutineDispatcher (or UnconfinedTestDispatcher) allows tests to control when coroutines run, enabling synchronous and deterministic coroutine testing.
Question 6: What is the purpose of the Truth assertion library in Android testing?
- To provide fluent, readable assertion methods as an alternative to JUnit assertions (Correct answer)
- To verify UI truth states
- To check permissions truthfully
- To validate JSON truthfulness
Correct answer: To provide fluent, readable assertion methods as an alternative to JUnit assertions
Google's Truth library provides a fluent API for writing assertions that produce more readable failure messages than standard JUnit assertions.
Which Espresso method is used to find a view by its resource ID?