Test in-app purchases on Android with a deterministic mock store
Android purchase testing usually stalls on sandbox setup, test accounts, propagation delays and cached state. A mock billing backend that mirrors production behaviour but lets you choose every outcome removes that friction. This guide shows how to use that approach to verify SDK connection, offerings, successful purchases, cancellations and failures in automated tests.
Why a mock store changes the testing problem
A mock billing backend is useful when it offers two properties: it is available immediately, and you control the result of each transaction. With no real payment processing, no test-account setup and no sandbox propagation wait, the test environment becomes deterministic. When a purchase dialog appears, the test can select success, failure or cancellation on demand. That control is what makes error paths repeatable instead of flaky, and lets many purchase-flow checks run in minutes without network latency or external state.
Set up the store, products and offering
Create the mock store from the dashboard under Apps & providers, then copy its API key. Create test products under Product Catalog, attach entitlements as needed, and add each product to an offering inside a package. Switching between test and live behaviour then becomes a matter of changing the API key. Before writing purchase tests, run this checklist: mock store enabled; test API key obtained; test products created; products placed in an offering package; key kept out of version control.
Choose instrumented tests for purchase flows
Android projects separate JVM unit tests from instrumented tests. JVM tests are fast but have no Android framework, so they cannot access Context, Activity or hardware. Instrumented tests run on a device or emulator with full framework access, at lower speed. Because SDK initialisation needs an Android context and purchases need an Activity, instrumented tests are the required choice here; Robolectric is an alternative that simulates the framework on the JVM but is not covered in this guide. Instrumented tests also exercise the real SDK against the mock backend, so a pass means the integration works rather than only that your own mocks agree with themselves.
Configure the SDK and protect the test key
Configure the SDK in a setup method that runs before each test. First obtain the application context from the instrumentation registry. Then initialise the SDK with the test API key, detailed debug logging for tests, and backend-completed purchases, which is the recommended mode and what the mock store expects. Production would use a quieter log level. Load the key from local.properties into BuildConfig so secrets stay out of version control, and use environment variables in CI instead. The protected modules for the source-set layout, context retrieval and SDK configuration accompany this page.
Verify connection, customer info and offerings first
Start with a connection test inside a coroutine test harness that waits for launched work and fails on exceptions. Fetch customer info: a successful call proves the key authenticates, a user is created or retrieved, and subscription data returns. Assert that the response, user identifier, first-seen timestamp and entitlements map are present and that the identifier is non-empty; a missing identifier breaks tracking, and a missing map breaks entitlement checks even for new users whose map may be empty. Next fetch offerings and check structural integrity: each map key matches its offering identifier, every offering has packages, and each package has a non-empty identifier plus a product with an ID and price. A null price would crash price display, so catching it in a test is the point. Finally verify the current offering has at least one package, handling the case where no current offering is configured.
Drive the full purchase flow with Espresso
Purchase calls need an Activity because the billing flow attaches to a lifecycle, may show UI, and the SDK validates that the Activity is active. Create a minimal test Activity that launches a purchase on the main thread inside a coroutine scope tied to the Activity lifecycle, cancels that scope on destroy to avoid leaks, and reports the result through a callback so the test thread can synchronise with the asynchronous purchase. For a successful purchase: fetch the named test offering and its first package, record initial active entitlements, launch the Activity, start the purchase, wait for the dialog, tap the valid-purchase option, then poll with a timeout until the callback fires. Assert no error occurred, active entitlements are now present, and the transaction contains the purchased product ID. Checking entitlements matters because a purchase that succeeds without granting them silently breaks premium features.
Distinguish cancellation from failure
Cancellation and failure look similar in the dialog but demand opposite app behaviour, so test them separately. For cancellation, tap the cancel option and assert an error arrives whose message indicates cancellation; the app should treat this as expected behaviour and avoid error UI. For failure, tap the failed-purchase option, assert an error arrives, then fetch customer info again and assert active entitlements did not increase. That last check catches incomplete error handling where a failed purchase still unlocks premium features. A useful decision rule: success must grant entitlements, cancellation must be recognised without alarming the user, and failure must grant nothing.
Run locally and in CI
Run instrumented tests with the Gradle connected test task, which needs a connected device or running emulator. You can run the whole module, filter to specific test classes, or enable verbose output. In CI, start an emulator and run the same task, then upload the test reports as an artifact so failures are inspectable. With that in place, offering fetching, purchase flows, entitlement granting and error handling are verified automatically on every build.
Frequently asked questions
Can purchase flows be tested as pure JVM unit tests?
No. The SDK needs an Android context and purchase calls need an active Activity, so purchase-flow tests belong in instrumented tests on a device or emulator. Pure JVM tests cannot reach those Android APIs.
Where should the test API key live?
Keep it out of version control. Load it from local.properties into BuildConfig for local runs, and supply it through environment variables in CI.
How do cancellation and failure differ in assertions?
A cancellation is expected user behaviour and should not trigger error UI. A failed purchase is a billing error and must not grant entitlements. The tests check both the error signal and, for failures, that active entitlements did not increase.