Android:在服务内部测试MediaPlayer

问题描述 投票:1回答:1

在我的应用中,有一项服务,其服务是在启动时播放/停止音频。我为此使用MediaPlayer

服务工作正常,现在我正在为此编写测试。我正在使用Robolectric的buildService方法创建服务。问题在于,在我的情况下,mediaplayer始终为空。这是我的服务的onStartCommand方法:

@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;
    }
  }

这是我的测试:

@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();
  }

有人可以帮我理解为什么mediaplayer变成null的原因。我猜可能是因为它使用了在Robolectric环境中不可用的本机方法。如果是这样,测试服务行为的最佳方法是什么?

android android-testing robolectric
1个回答
0
投票

[经过https://github.com/robolectric/robolectric/issues/3855并调试了一段时间之后,我意识到我们必须手动在MediaInfo中填充ShadowMediaPlayer对象才能起作用。

这是我所做的(现在可以完美运行了:):]

在实例化播放器之前添加了此行:

ShadowMediaPlayer.addMediaInfo(
        DataSource.toDataSource(
            "android.resource://"
                + getApplicationContext().getPackageName()
                + "/"
                + <resource id of audio file>),
        new MediaInfo(17, 0));
© www.soinside.com 2019 - 2024. All rights reserved.