Issue
In my app, there's a service whose job is to play/stop an audio when it's started. I am using MediaPlayer
for this.
Service works fine and now I am writing tests for it.
I am using Robolectric's buildService
method to create the service.
The problem is that mediaplayer
always comes out to be null in my case.
Here's my service's onStartCommand
method:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (ACTION_START.equals(intent.getAction())) {
try {
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.holdmusic);
} catch (Exception e) {
Log.e(TAG, "not able to prepare media player", e);
Toast.makeText(this, R.string.not_able_prepare_media_player, Toast.LENGTH_SHORT).show();
stopSelf();
return START_NOT_STICKY;
}
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mediaPlayer.setOnCompletionListener(mediaPlayer -> onStop()); // mediaplayer always comes out to be null here in my test
mediaPlayer.start();
mediaSession = new MediaSession(getApplicationContext(), getString(R.string.app_name));
showNotification();
return START_STICKY;
} else if (ACTION_STOP.equals(intent.getAction())) {
onStop();
return START_NOT_STICKY;
} else {
// called with unknown action, should not happen
stopSelf();
return START_NOT_STICKY;
}
}
Here's my test:
@Test
public void testActionStart() {
Intent serviceIntent =
new Intent(ApplicationProvider.getApplicationContext(), MediaPlayerService.class);
serviceIntent.setAction(MediaPlayerService.ACTION_START);
MediaPlayerService service =
Robolectric.buildService(MediaPlayerService.class, serviceIntent)
.create()
.startCommand(0, 0)
.get();
ShadowService shadowService = Shadow.extract(service);
assertThat(service.isPlaying()).isTrue();
assertThat(shadowService.getLastForegroundNotification()).isNotNull();
}
Can someone please help me understand why mediaplayer is coming out to be null. I guess maybe because it uses native methods which are not available in robolectric environment. If that's the case,what's the best way to test the service's behaviour?
Solution
After going through https://github.com/robolectric/robolectric/issues/3855 and debugging for a while, I realised that we have to manually populate the MediaInfo
object in the ShadowMediaPlayer
for it to work.
Here's what I did (and it works perfectly now):
Added this line just before instantiating the player:
ShadowMediaPlayer.addMediaInfo(
DataSource.toDataSource(
"android.resource://"
+ getApplicationContext().getPackageName()
+ "/"
+ <resource id of audio file>),
new MediaInfo(17, 0));
Answered By - Yash
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.