繁体   English   中英

Android 测试用例中的权限

[英]Permission in Android test case

我的应用程序应该在一段时间(几小时或几天)后有一些变化,我想测试一下。

我尝试在我的单元测试中使用 SystemClock.setCurrentTimeMillis() 来模拟时间/日期的变化,但没有任何运气。

我在应用程序和测试应用程序的清单中声明了<uses-permission android:name="android.permission.WRITE_SETTINGS" /> ,这并没有改变任何东西。

目前,我正在模拟器上运行这些测试,如果这有什么不同的话......

编辑:在尼克的帮助下,还请求了 SET_TIME 权限:

<uses-permission android:name="android.permission.SET_TIME" />

但是现在,logcat 显示:

WARN/PackageManager(59): Not granting permission android.permission.SET_TIME to package com.matthieu.tests (protectionLevel=3 flags=0xbe46)

另一个编辑:用 dtmilano 的回答...

在我的测试中添加了这段代码(使用正确的 try/catch):

Runtime.getRuntime().exec("date \"$((10800 + $(date +%s)))\"").waitFor();

当我在 shell 上运行 go 时,我可以毫无问题地运行该命令,并且我看到模拟器中的时间发生了变化(我试图增加 3 小时)。 当我用我的代码运行测试时,时间根本不会改变......?

我在命令行上做的是:

date "$((10800 + $(date +%s)))"

我怀疑我需要在 Runtime.exec 中添加“adb shell”部分...

似乎这是在正确的道路上,但仍然无法让它运行。 它也可能是 go ,正如尼克指出的那样,它需要一个系统进程才能改变时间......?

如果您需要更改时区,请将 android.permission.SET_TIME_ZONE 添加到您的清单中,

然后从您的活动中(或您需要的任何地方..但您需要获取适当的上下文..)

Context context = getContext(); // or (Context) this, or whatever depending on where you are
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mgr.setTimeZone(timezoneid); // replace timezoneid with the time zone you need e.g. "pacific/Auckland"
mgr.setTime(timeinmillis); // replace timeinmillis with the time you need in millis, probably from a Date or Calendar object... but watch the timezone in the calendar ;-)

重点是 AlarmManager 系统服务包含设置系统时间和时区的成员..

http://developer.android.com/reference/android/Manifest.permission.html#SET_TIME

我搜索了“android 权限”,然后在权限页面上找到了“时间”这个词。 如果您已通过 api 8 级,我建议您请求该权限。

更新:基于链接,我认为无法从用户空间应用程序设置系统时间。 出于测试目的,您可能需要手动更改模拟器上的时间。 我发现的唯一其他选择需要构建并签署您自己的 Android 构建。

从您的主机(假设您使用的是 linux),您可以运行:

$ adb shell date $(date --date='2011-06-11 12:10:10' +%s.0)

主要是模拟器。 将日期和时间替换为所需的值。 您应该找到一种将此更改与您的测试同步的方法,或者您甚至可以使用Runtime.exec()从您的测试中运行它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM