我正在使用Robolectric(版本 3)为我的 Android 项目编写测试用例。这是我的简单测试场景:
被测函数为:
public class MyClass {
private Context mContext;
public MyClass(Context context) {
mContext = context;
}
//function under test
public boolean isScreenOn() {
PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
return powerManager.isScreenOn();
}
}
(我知道isScreenOn()已从 android API 版本 20 中弃用,但我的测试设置为针对 android API 17 运行)
测试函数为:
@Test
@Config(sdk = Build.VERSION_CODES.JELLY_BEAN_MR1)
public void testIsScreenOn() {
//get Context
Context context = ShadowApplication.getInstance().getApplicationContext();
//get power manager
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//get shadow power manager
ShadowPowerManager shadowPowerManager = Shadows.shadowOf(powerManager);
//set screen off
shadowPowerManager.setIsScreenOn(false);
//isScreenOn() in MyClass returns true, why?
MyClass myObj = new MyClass(context);
AssertFalse(myObj.isScreenOn()); //Failed!
}
虽然我使用了 ShadowPowerManager实例setIsScreenOn(false)
,但被测函数仍然为 isScreenOn() 返回 true。为什么?