浓咖啡:想要匹配1个意图。实际匹配的2个意图

时间:2019-08-17 17:29:57

标签: android android-espresso

我知道这里已经有很少的类似问题,但是没有答案可以解决我的问题。

我正尝试测试我的 MainActivity 是否在2秒后从 SplashActivity 开始。

这是我的考试:

@RunWith(AndroidJUnit4::class)
@LargeTest
class SplashActivityTest {

    @get:Rule
    val rule = ActivityScenarioRule(SplashActivity::class.java)
    private val splashScreenWaitingTime = 2000L

    @Before
    fun setup() {
        Intents.init()
    }

    @After
    fun teardown() {
        Intents.release()
    }

    @Test
    fun navigateToMainScreenAfter2Secs() {
        val idlingRes = ElapsedTimeIdlingResource(splashScreenWaitingTime)
        IdlingRegistry.getInstance().register(idlingRes)
        intended(hasComponent(MainActivity::class.java.name))
        IdlingRegistry.getInstance().unregister(idlingRes)
    }
}

以上测试绝对可以。但是如果我添加其他测试并且该测试在上述测试之前运行,就会出现问题。例如,假设我添加了另一个空测试,如下所述:

@Test
fun test() {
    // No code here
}

由于所有测试用例均独立运行,因此如果 test() navigateToMainScreenAfter2Secs()之前运行,那么我会收到错误消息:androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: Wanted to match 1 intents. Actually matched 2 intents.

我知道使用times(2)可以解决问题。但不确定为什么吗?为什么即使添加一个空测试用例,意图也会匹配两次?

如果您怀疑我的生产代码可能有问题,那么这里是生产代码:

class SplashActivity : AppCompatActivity() {

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

    override fun onResume() {
        super.onResume()
        Thread(Runnable {
            Thread.sleep(2000)
            runOnUiThread {
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
            }
        }).start()
    }
}

我在这里错过了什么吗?即使我为每个测试用例都释放了意图,是什么导致意图触发两次?

0 个答案:

没有答案