Android测试用例的权限

时间:2011-06-08 23:14:29

标签: android unit-testing

我的应用程序应该在一段时间后(几小时或几天)进行一些更改,我想测试一下。

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

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

目前,我正在模拟器上运行这些测试,如果这有任何区别......

编辑:在Nick的帮助下,还请求了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时,我可以毫无问题地运行该命令,并且我在模拟器中看到时间正在变化(我试图添加3个小时)。当我用我的代码运行测试时,时间根本不会改变......?

我在命令行上做的是:

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

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

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

3 个答案:

答案 0 :(得分:2)

如果您需要更改时区,请将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系统服务包含用于设置系统时间和时区的成员。

答案 1 :(得分:1)

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

我在权限页面上搜索了“android权限”,找到了“时间”这个词。如果你已经过了api等级8,我会建议你请求这个许可。

更新:根据this链接,我认为无法从用户空间应用设置系统时间。出于测试目的,您可能需要手动更改模拟器上的时间。我找到的唯一其他选项需要构建和签署自己的Android版本。

答案 2 :(得分:1)

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

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

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

相关问题