如何在 Android 中为仪器测试创建隔离上下文

How create an isolated context in Android for instrumented test

我想 运行 一些测试使用 AccountManager 添加和获取帐户,但我想在新的上下文中执行这些操作,而不需要我在模拟器中已有的帐户。

可以吗?

我的例子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))
    }
}

我使用 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