Google Flutter Google Flutter Testing 2 — Questions and Answers
Question 1: Which package is the standard choice for mocking dependencies in Flutter unit and widget tests?
- fake_async
- mockito (Correct answer)
- mocktail
- test_double
Correct answer: mockito
mockito is the widely used Dart mocking library that generates mock classes via code generation with @GenerateMocks.
Question 2: What does the expect() function do in a Flutter test?
- It registers a test case
- It asserts that the actual value matches the matcher (Correct answer)
- It pumps the widget tree
- It navigates to the next screen in a test
Correct answer: It asserts that the actual value matches the matcher
expect() compares an actual value against a matcher (like equals(), isTrue, findsOneWidget) and fails the test if they don't match.
Question 3: Which matcher verifies that exactly one matching widget exists in the widget tree?
- findsWidgets
- findsOneWidget (Correct answer)
- findsAny
- matchesWidget
Correct answer: findsOneWidget
findsOneWidget asserts that exactly one widget matching the finder exists in the widget tree.
Question 4: What is the purpose of setUp() in Flutter tests?
- It defines the widget under test
- It runs code before each test case to initialize shared state (Correct answer)
- It mounts the widget tree
- It registers a teardown hook
Correct answer: It runs code before each test case to initialize shared state
setUp() runs its callback before every individual test case, making it suitable for initializing mocks or resetting state.
Question 5: How do you simulate a user tapping a widget in a Flutter widget test?
- tester.click()
- tester.tap() (Correct answer)
- tester.press()
- tester.touch()
Correct answer: tester.tap()
WidgetTester.tap() simulates a touch at the center of the widget found by a Finder.
Question 6: Which tool is used to verify code coverage in a Flutter project?
- flutter analyze
- flutter test --coverage (Correct answer)
- flutter coverage
- dart coverage
Correct answer: flutter test --coverage
Running flutter test --coverage generates an lcov.info file in the coverage/ directory that tools like genhtml can render as an HTML report.
Which package is the standard choice for mocking dependencies in Flutter unit and widget tests?