Search code examples
androidaccountmanagerinstrumented-test

How create an isolated context in Android for instrumented test


I want to run some test adding and getting accounts using AccountManager but I want to do the operations in a new context without the account I already have in the emulator.

Is it possible to do that?

Example of my class

@RunWith(AndroidJUnit4::class)
class AccountTest {

    private val ACCOUNT_TYPE = "com.android.account"

    private lateinit var accountManager: AccountManager

    @Before
    fun init() {
        accountManager = AccountManager.get(ApplicationProvider.getApplicationContext())
    }

    @Test
    fun addAccountTest(){
        val account = Account("test", ACCOUNT_TYPE)
        val result = accountManager.addAccountExplicitly(account, null, null)

        assertThat(result, `is`(true))
    }

    @Test
    fun getAccountTest() {
        val accountList = accountManager.getAccountsByType(ACCOUNT_TYPE).toList()

        assertThat(accountList.size, `is`(0))
    }
}

Solution

  • I solved the issue using Robolectric :)

    Unlike traditional emulator-based Android tests, Robolectric tests run inside a sandbox which allows allows the Android environment to be precisely configured to the desired conditions for each test, isolates each test from its neighbors, and extends the Android framework with test APIs which provide minute control over the Android framework’s behavior and visibility of state for assertions.

    robolectric.org