Search code examples
androidunit-testingwakelock

How would you unit test an Android app that needs to go into sleep mode, come out, and record results?


I know this seems like an odd question, but I need to :

  1. grab info before sleep
  2. sleep
  3. do tasks
  4. wake up
  5. get assert results

What I have tried is to enable the sleep in the set up portion of the test, unfortunately it kills everything (which I know is supposed to happen by android's standards).

Thanks, Kelly


Solution

  • Ah ha!

    OK, at least for making sure to study the state of the screen. You want to do the following:

    In your emulator, go to the Settings \ Applications \ Developement area and uncheck "Stay Awake"

    At this point, lock your emulator. You should see the lock screen.

    Now, run your test for the wake lock.

    For me I have done the following (which uses roboguice 1.1.2)

    @MediumTest
    public void test_And_Screen_Is_In_Sleep_It_Should_Not_Make_Screen_Bright() throws Exception
    {
        //currently test hates this even after I have assigned it the proper rights
        //to quote Ted Striker: What a pisser! :)
        //_power.get().goToSleep(0);
    
        boolean screenOn = _power.get().isScreenOn();
    
        assertFalse(screenOn);
    
        if (!screenOn)
        {
            _wake.get();
    
            boolean screenOn1 = _power.get().isScreenOn();
    
            assertFalse(screenOn1);
        }
    
        if (_wake != null)
        {
            _wake.release();
        }
    }
    

    I have an interface called IWake like so:

    public interface IWake
    {
        void get();
    
        void release();
    }
    

    In the implementation for IWake I simply setup the class to do all the heavy lifting for acquiring (get()) and release( which is also release())

    For force the testing device to lock, I came up with a great idea since you (typically) can't use that sleep method in the PowerManager.

    Do this!

    In my test method I did this for the setup:

    @Override
    public void setUp() throws Exception
    {
        super.setUp();
    
        _pwr = (PowerManager) getInstrumentation().getContext().getSystemService(Context.POWER_SERVICE);
    
        //setup timeout which is part of: android.provider.Settings.System
        System.putInt(getInstrumentation().getContext().getContentResolver(), System.SCREEN_OFF_TIMEOUT, 0);
    }
    

    Basically I decided to change the timeout to 0 in the settings. Since this happens it locks it instantly. How freakin' cool is this? :) Anyways, I hope this helps others

    Cheers, Kelly