I am using Robolectric (version 3) to write test case for my Android project. Here is my simple test scenario:
The function under test is :
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();
}
}
(I know isScreenOn() is deprecated from android API version 20, but my test is set to be run for android API 17)
The test function is:
@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!
}
Though I have used ShadowPowerManager instance to setIsScreenOn(false)
, the function under test still returns true for isScreenOn(). Why?