Google Professional Cloud Developer Question 275
Select 2Google Cloud PlatformYou are developing a serverless application on Google Cloud using Cloud Functions. The function fetches data from a Firestore database and performs some business logic. You want to implement unit tests for this function, ensuring they run efficiently and independently of external resources (e.g., Firestore). How should you design your unit tests?
- A
Use a Firestore emulator to simulate database operations during your unit tests.
- B
Mock the Firestore client and define expected responses for database calls.
- C
Write tests that directly query the Firestore database to validate the function's behavior.
- D
Stub the Firestore API to simulate specific scenarios without initiating actual requests.
- E
Use integration tests instead of unit tests since the function involves external dependencies.
Show answer and explanation
Correct answers: B, D
Explanation
Unit tests should focus on testing isolated components of your application without relying on external dependencies. Mocking and stubbing are effective strategies for isolating dependencies like Firestore in unit tests. This ensures the tests are efficient, reliable, and independent of external resources, adhering to best practices for unit testing in cloud-native applications.
- A. Incorrect.
Using a Firestore emulator is more suitable for integration tests, as it involves simulating the full database behavior. Unit tests should isolate dependencies and not interact with actual or emulated resources.
- B. Correct.
Mocking the Firestore client is an appropriate approach for unit testing, as it allows you to define expected responses and isolate your function's logic from the actual Firestore service.
- C. Incorrect.
Directly querying Firestore in unit tests violates the principle of isolation, as the tests will rely on external services, making them slower and potentially flaky.
- D. Correct.
Stubbing the Firestore API is another valid strategy for unit testing, as it allows you to simulate specific scenarios and control the behavior of external dependencies without making real requests.
- E. Incorrect.
Integration tests are complementary to unit tests but should not replace them. Unit tests are designed to test small, isolated pieces of functionality, while integration tests validate the interaction between components.