android - 使用 Espresso 解锁模拟器屏幕

标签 android android-espresso

我正在开发我的第一个 Android 应用程序,并且正在设置 CI 服务器。我的 Espresso 测试在我的机器上运行良好,但 travis 出现以下错误

java.lang.RuntimeException: Waited for the root of the view hierarchy to have window focus and not be requesting layout for over 10 seconds.

看来我需要在运行测试之前解锁模拟器屏幕。为此,我必须使用所需的权限向 src/debug 添加 list ,然后使用以下命令解锁屏幕:

KeyguardManager mKeyGuardManager = (KeyguardManager) ctx.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mLock = mKeyGuardManager.newKeyguardLock(name);
mLock.disableKeyguard();

问题是我不想用 if block 中包含的上述代码乱丢我的 Activity 。有没有办法从 Espresso 测试本身解锁屏幕?

我的 Espresso 测试:

@RunWith(AndroidJUnit4.class)
public class EspressoSetupTest {

    @Rule
    public final ActivityTestRule<WelcomeActivity> activity =
            new ActivityTestRule<>(WelcomeActivity.class, true, true);

    @Test
    public void launchTest() {
        onView(withId(R.id.welcome_textView_hello))
                .perform(click())
                .check(matches(withText("RetroLambda is working")));
    }
}

最佳答案

您可以在 Espresso 测试中使用 setUp() 方法,例如:

@UiThreadTest
@Before
public void setUp() throws Exception {
   final Activity activity = mActivityRule.getActivity();
    mActivityRule.runOnUiThread(new Runnable() {
        @Override
        public void run() {
          KeyguardManager mKG = (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE);
          KeyguardManager.KeyguardLock mLock = mKG.newKeyguardLock(KEYGUARD_SERVICE);
          mLock.disableKeyguard();

        //turn the screen on
         activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
          }
      });
}

src/debug/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" >
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
</manifest>

关于android - 使用 Espresso 解锁模拟器屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33872777/

相关文章:

java - 在 Espresso 测试中断言 ProgressBar 的进度

刚刚安装的Android studio,gradle报错

android - Espresso 测试单独通过,在套件中运行时失败

android - 新的 Google 地方信息自动填充功能及其定价

android - 顶点着色器不在 galaxy tab10 (tegra 2) 上运行

java - 安卓 Espresso : PerformException

Android Espresso 自动化测试中的谓词?

Android java.lang.UnsatisfiedLinkError dalvik.system.PathClassLoader

java - Android从原始共享按钮音频

android - 日期变量自动获取到 1970 年的年份。它必须是 2015 年