Search code examples
androidjunitmedia-player

Android MediaPlayer OnCompletionListener not called in JUnit Testcase (AndroidTestCase)!


I am using the Android MediaPlayer class and trying to write a testcase which verifies that the onCompletion method is called. I use it to play the next track after the previous one is finished.

When I run the app using the emulator (2.1 or 4.0) the onCompletion method is called and the next track starts playing, but in the testcase it is not. Here is the simplified code:

public class MediaPlayerControllerTest extends AndroidTestCase implements OnCompletionListener {

    public void testContinuePlayNextTrack() {
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
        try {
            mediaPlayer.setDataSource("/mnt/sdcard/5749/01.mp3");
            mediaPlayer.prepare();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mediaPlayer.start();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        System.out.println("ON COMPLETION!!!!!");
    }
}

The code above is normally part of a class MediPlayerController which is used in the app and the test, so it's the same class. I broke the problem down to the few lines of code above.

This cost me a lot of hours. I hope someone has a solution!

Thanks a lot!!!


Solution

  • I think the problem is that your test case is no longer running when the MediaPlayer finishes playing the mp3. So your solution is to keep the test case alive until the onCompletion() is fired.

    I had a similar issue when playing a file from an IntentService. The Service was being destroyed before the callback was initiated.