1

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?

Egor
  • 39,695
  • 10
  • 113
  • 130
user842225
  • 5,445
  • 15
  • 69
  • 119
  • I just copy/pasted this to run it and it seemed to work fine, the assert confirmed what I set in the shadow before (I tried flipping true/false to double check). Is the assert failing or do you have any other exceptions? Are you running this with a RobolectricTestRunner? – Alex Florescu Oct 12 '15 at 12:39

1 Answers1

0

Same as Alex Florescu I tried just to run your test (https://github.com/emartynov/robolectic-experiments/commit/065f6d2d5b008a4e4dc9bd3fac27ee8f8d650dc0).

But I was not able to repro. The only one difference that I see I run it with API21.

Is running it on on lower API something critical for you?

Eugen Martynov
  • 19,888
  • 10
  • 61
  • 114