2015-07-19 87 views
2

我必須測試具有視頻的屏幕飛濺,當視頻完成其他活動時,視頻持續時間爲11秒。測試等待VideoView完成以開始新活動robolectric 3

我有後續的測試類:

public class ScreenSplashTest { 

    private ShadowActivity screenSplash; 
    private ShadowVideoView videoView; 

    @Before 
    public void setUp(){ 
     ScreenSplash screenSplashActivity = Robolectric.buildActivity(ScreenSplash.class).create().get(); 
     screenSplash = Shadows.shadowOf(screenSplashActivity); 
     VideoView videoViewWidget = (VideoView)screenSplash.findViewById(R.id.videoViewSplash); 
     videoView = Shadows.shadowOf(videoViewWidget); 
    } 

    @Test 
    public void activityStarts_VideoStartsToPlay() throws Exception{ 
     assertTrue(videoView.isPlaying()); 
    } 
    @Test 
    public void whenVideoFinish_StartsChooseTeamActivity() throws Exception{ 
     videoView.stopPlayback(); 
     Intent nextActivity = screenSplash.getNextStartedActivity(); 
     assertEquals(nextActivity.getComponent().getClassName(), ChooseTeamActivity.class.getName()); 
    } 
} 

這是我ScreenSplash活動:

public class ScreenSplash extends ActionBarActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_screen_splash); 
     getSupportActionBar().hide(); 
     this.getWindow().getDecorView().setBackgroundColor(0xffffff); 

     VideoView videoView = (VideoView) findViewById(R.id.videoViewSplash); 

     Uri videoFile = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.splash); 
     videoView.setVideoURI(videoFile); 

     videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
      @Override 
      public void onCompletion(MediaPlayer mediaPlayer) { 
       Intent i = new Intent(getApplicationContext(), ChooseTeamActivity.class); 
       startActivity(i); 
      } 
     }); 

     videoView.start(); 
    } 
    } 

的問題是我怎麼能寫這樣的代碼測試?

回答

2

您可以從ShadowVideoView的getOnCompletionListener中獲取MediaPlayer.OnCompletionListener,然後調用它的onCompletion方法。您可以模擬MediaPlayer對象。 一種可能的代碼片斷:

 assertTrue(videoView.isPlaying()); 
    MediaPlayer.OnCompletionListener completionListener = videoView.getOnCompletionListener(); 
    completionListener.onCompletion(mock(MediaPlayer.class)); 
    Intent intent = screenSplash.getNextStartedActivity(); 
    assertNull(intent); 
    assertEquals(ChooseTeamActivity.class.getName(), intent.getComponent().getClassName()); 

這種方法將能夠測試上面的代碼。如果您正在考慮視頻的實際完整播放,然後執行監聽器代碼,那麼此類方法將不會按照單元測試方法進行。我們測試書面代碼的功能,而不是底層框架。 在這種情況下,您的測試代碼應測試一個有效的URI,檢查它的播放與否以及偵聽器是否執行所需的操作。 通過MediaPlayer對象測試偵聽器也將是底層android代碼的測試,而不僅僅是您的代碼。

+0

ohh thak你:)我非常喜歡單元測試泰克的指導 – kentverger