如何测试活动是否未使用Robolectric进行路由?

时间:2018-04-16 06:39:49

标签: android kotlin robolectric

我的活动很简单:

class HomeActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)

        if (!this.userPreference.memberRegistered) {
            goToActivity(AuthActivity::class.java)
        }
    }
}

因此,如果用户已注册,则会保留HomeActivity,否则会转到AuthActivity

userPreferenceSharedPreference的包装器。在另一个代码库中运行良好且经过良好测试。

我首先尝试RuntimeEnvironment来自Robolectric是否可以解决这个问题,当然这是有效的。

@Test
fun try_test() {
    val userPreference = UserPreference(
        Settings(SETTINGS_NAME, RuntimeEnvironment.application.applicationContext)
    )

    // default value should be false, PASS
    assertEquals(false, userPreference.memberRegistered)

    // change it to true, then it should be true, PASS
    userPreference.memberRegistered = true
    assertEquals(true, userPreference.memberRegistered)
}

然后我尝试了AuthActivity的路由是否有效,并且它有效。测试通过。

@Test
fun should_go_to_AuthActivity_when_1st_start() {
    val homeActivity = Robolectric.setupActivity(HomeActivity::class.java)
    val expectedIntent = Intent(homeActivity, AuthActivity::class.java)
    val actual = ShadowApplication.getInstance().nextStartedActivity
    assertEquals(expectedIntent.component, actual.component)
}

问题

然后问题是我不知道在HomeActivty时检查活动是否保持在this.userPreference.memberRegistered = true。由于actual is null的原因,以下测试失败。这是因为没有路由发生,所以nextStartedActivity为空,但如何验证它是否在测试中保持此活动?

@Test
fun should_stay_at_HomeActivity_when_already_member() {
    val userPreference = UserPreference(
        Settings(SETTINGS_NAME, RuntimeEnvironment.application.applicationContext)
    )

    userPreference.memberRegistered = true

    val actual = ShadowApplication.getInstance().nextStartedActivity
    assertEquals(
        actual.component.shortClassName,
        ".ui.home.HomeActivity"
    )
}

0 个答案:

没有答案