我正在开发我的第一个 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/