android - 手机锁定/休眠时不调用 ActivityInstrumentationTestCase2 中的 onCreate()

标签 android testing android-activity android-emulator

我正在使用 ActivityInstrumentationTestCase2 编写测试。

当模拟器打开并且 Activity 可以进入前台时,我的测试完美运行。

当我在手机锁定的情况下开始测试时,不会创建 Activity 。 这似乎是“有道理的”,因为如果无法获得前台(手机已锁定!),则没有理由加载 Activity 。但是,在运行测试套件时,这会导致漏报...

这是一个示例测试

public void testSplashscreenRedirectsSomewhereAfterTimeout() throws Exception {

    Instrumentation.ActivityMonitor monitor = getInstrumentation().addMonitor(SomeActivity.class.getName(), null, false);

    getActivity(); // to make sure that the activity gets launched
    Activity activity = monitor.waitForActivityWithTimeout(10000); // waiting for the other activity
    assertNotNull("BaselineActivity was not called", activity);
}

当手机被锁定时,getActivity() 返回正确的 Activity ,但它的 onCreate() 方法永远不会被调用。

有什么方法可以让测试在屏幕锁定的情况下也能正常工作?

最佳答案

假设您关于没有创建 Activity 的说法是正确的,为什么不直接使用 KeyGuardManager 解锁手机呢? .除非在手机锁定和解锁时必须执行特定操作,或者您正在测试服务,否则我只会运行“准备测试环境”功能来检查屏幕是否已锁定,解锁它并运行你的测试。

How to tell if your screen is unlocked .如果没有,则解锁它并运行您的测试。

KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE); 
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();

更新

使用以下命令关闭 Key Guard Lock

//Get the current window 
Window window = getWindow();  
//Add the Flag from the window manager class
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

关于android - 手机锁定/休眠时不调用 ActivityInstrumentationTestCase2 中的 onCreate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7263899/

相关文章:

android - 如何知道 CustomAdapter 正在处理哪个 Activity ?

android - 第二次设置适配器时不显示 ListView

android - Activity 背景

Android 外部数据存储问题

android - 为 android 构建 valgrind 时未定义 __ANDROID__

android - 我应该使用 GoogleAuthUtil.getToken(...) 吗?

unit-testing - 为什么模拟类(class)这么糟糕?

android - 如何为较小密度的屏幕准备图像?

java - 我如何模拟一个带有私有(private)字段的类?

ios - Xcode项目测试和Pre-release内测的区别