gpt4 book ai didi

android - 如何验证 IntentService 启动

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:34:16 26 4
gpt4 key购买 nike

我正在尝试使用 Espresso-2.2 测试我的应用程序行为

在主要 Activity 中,当按下按钮时,服务和另一个 Activity 都将启动:

public class MainActivity extends Activity {

public void onButtonClicked() {
startActivity(SecondActivity.getStartIntent());
startService(MyIntentService.getStartIntent());
}
}

我正在测试预期的组件是否正在启动:

public class MainActivityTest {
@Rule
public final IntentsTestRule<MainActivity> intentsRule = new IntentsTestRule<>(MainActivity.class, true);

@Test
public void shouldStartServiceOnButtonClicked() {
onView(withId(R.id.button)).perform(click());
intended(hasComponent(hasClassName(SecondActivity.class.getName())));
intended(hasComponent(hasClassName(MyIntentService.class.getName())));
}
}

但是我得到了错误:

Caused by: junit.framework.AssertionFailedError: Wanted to match 1 intents. Actually matched 0 intents.

IntentMatcher: has component: has component with: class name: is "com.example.MyIntentService" package name: an instance of java.lang.String short class name: an instance of java.lang.String

Matched intents:[]

Recorded intents:
-Intent { cmp=com.example/.SecondActivity (has extras) } handling packages:[[com.example]], extras:[Bundle[...]])
at junit.framework.Assert.fail(Assert.java:50)

SecondActivity 的开始已注册。为什么我的 IntentService 启动未注册(我检查过它已启动)?

最佳答案

tl;dr 考虑到当前的 espresso-intents 提供的功能,这似乎不太可能

我在源代码中四处寻找,因为我正在尝试做类似的事情,这是我发现的:

“Intent ”匹配器通过查看记录的 Intent 列表来工作。这些由调用 Intents.init() 时注册到 IntentMonitor 实例的回调进行跟踪。 IntentMonitor 实例由当前 Instrumentation 定义。任何时候调用 IntentMonitor 的 signalIntent() 时,都会触发 Intents 中的回调。

问题在于,如果您以 Intent 调用 activity.startService(),则 signalIntent() 从未真正被调用。这是因为 AndroidJunitRunner 案例中的 signalIntent() 仅由在 ExposedInstrumentationApi 上公开的方法调用(恰好仅与各种 startActivity() 方法相关)。为了将 espresso-intents 与 startService() 一起使用,似乎需要为 startService() 提供一个检测 Hook ,以允许在 IntentMonitor 上调用 signalIntent()。

我没有向我的测试 apk 添加自定义 Instrumentation 的经验,但这将是我的下一个调查途径。如果我发现任何有用的东西,我会更新我的答案。

关于android - 如何验证 IntentService 启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31520613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com