System service testing

168 views
Skip to first unread message

Nike Dev

unread,
May 15, 2013, 6:34:40 AM5/15/13
to robol...@googlegroups.com
How I can test a system service? In my case I need to test DevicePolicyManager. Below piece of my code:

public class DeviceAdministratorHelper {

    DevicePolicyManager devicePolicyManager;
    ComponentName adminComponentName;


    public DeviceAdministratorHelper(Context context) {
        devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
        adminComponentName = new ComponentName(context, AdminBroadcastReceiver.class);
    }

    public void lockDeviceNow() {
       devicePolicyManager.lockNow();
    }
}

Should I create a shadow class? Or what I should do?

Johannes Elgh

unread,
May 24, 2013, 1:42:28 AM5/24/13
to robol...@googlegroups.com
Cannot get this to work myself. Please post here if you got it to work!

Nike Dev

unread,
Jul 18, 2013, 7:07:41 AM7/18/13
to robol...@googlegroups.com
Guys from Robolectric, help me please. I really need your advice. 
I can not test class which contains some system service.
Now I use Robolectric 2.1

For example my class:
public class PlayTrackService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        _performPlaying();
        return START_NOT_STICKY;
    }

    private void _performPlaying(){
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.setSpeakerphoneOn(true);
        audioManager.setMode(AudioManager.MODE_IN_CALL );

        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 3, 0);

        MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.simple_track);
        mp.setLooping(true);

        mp.start();
    }
}

There is my test:
@Test
@Config(shadows = {ShadowAudioManager.class})
public void testOnStartCommand() throws Exception {
    PlayTrackService service = new PlayTrackService();
    int res = service.onStartCommand(new Intent(), Service.START_NOT_STICKY,1);
    assertEquals(Service.START_NOT_STICKY, res);
    service.onDestroy();
}

But when I run test I have NullPointerException when I try get AudioManager
in this string: AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

May be I have wrong way to perform test? Explain please how I can do this correctly
Reply all
Reply to author
Forward
0 new messages