2015-08-18 236 views
0

所以我有這個運行良好的Splash屏幕,但我想測試「是處理程序已經發起了下一個活動」。 類:Android測試初始屏幕

public class SplashActivity extends Activity { 
private final int SPLASH_DISPLAY_LENGTH = 3000; 
private TextView quote_text; 

private int[] quote_id = {R.string.quote_1, R.string.quote_2, R.string.quote_3, R.string.quote_4, R.string.quote_5}; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.splashscreen); 

    quote_text = (TextView) findViewById(R.id.quote_text); 

    int idx = new Random().nextInt(quote_id.length); 
    int selectedID = (quote_id[idx]); 
    quote_text.setText(getResources().getText(selectedID)); 

    new Handler().postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class); 
      SplashActivity.this.startActivity(mainIntent); 
      SplashActivity.this.finish(); 
     } 
    }, SPLASH_DISPLAY_LENGTH); 
} } 

Robolectric: 測試,這是失敗在
的assertEquals(expectedIntent,shadowOf(活性).getNextStartedActivity());

@Test 
    public void testNextActivityWasLaunchedWithIntent() { 
     SplashActivity activity =  Robolectric.buildActivity(SplashActivity.class).create().start().resume().get(); 
     assertNotNull("MainActivity is not instantiated", activity); 

    synchronized (this) 
    { 
     try { 
      this.wait(3200); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

    Intent expectedIntent = new Intent(activity, MainActivity.class); 
    assertNotNull(expectedIntent); 

    assertEquals(expectedIntent,shadowOf(activity).getNextStartedActivity()); 
} 

誰能告訴我請,我怎麼能測試中,處理程序解僱我的下一個活動? 非常感謝!

回答

1

這是可以通過一些流行的單元測試框架,你可以用來檢查開始正確的意圖。請參閱Robolectric的以下文檔。

http://robolectric.org/writing-a-test/

Intent expectedIntent = new Intent(activity, WelcomeActivity.class); 
assertThat(shadowOf(activity).getNextStartedActivity()).isEqualTo(expectedIntent); 
+0

嘿Durgesh,我已經更新了我的答案,pelase評論。謝謝 – Karoly

0

我能夠做成功測試閃屏在我的應用程序如下:

public void test(){ 
ActivityController<SplashScreen> controller = Robolectric.buildActivity(SplashScreen.class).create().start(); 
ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); 

SplashScreen splashScreenActivity = controller.get(); 
Intent expectedIntent = new Intent(splashScreenActivity, PrimeiroAcessoActivity.class); 

assertEquals(expectedIntent,shadowOf(splashScreenActivity).getNextStartedActivity());} 

在我看來,你錯過了ShadowLooper.runUiThreadTasksIncludingDelayedTasks()線。需要運行Handler.postDelayed內部的代碼,如this StackOverflow post中所述。