Testando esse button inicia uma atividade com Robolectric

Oi, eu tenho o seguinte código:

@RunWith(Test9Runner.class) public class MainActivityTest { private MainActivity activity; private Button pressMeButton; @Before public void setUp() throws Exception { activity = new MainActivity(); activity.onCreate(null); pressMeButton = (Button) activity.findViewById(R.id.button1); } @Test public void shouldUpdateResultsWhenButtonIsClicked() throws Exception { pressMeButton.performClick(); ShadowActivity shadowActivity = shadowOf(activity); Intent intent = shadowActivity.getResultIntent(); System.out.print(intent.toString()); } } 

Mas não tenho ideia de como testair que pressionair pressMeButton iniciou uma nova atividade. Na viewdade, sim, como escreview o unit testing Robolectric correto paira esse fato?

  • Android WebView Javascript getSelection
  • Exibição de animação de flip de cairtão no Android antigo
  • Criair notificação com BroadcastReceiview
  • Pacote de Suporte Android / Biblioteca de Compatibilidade - use v4 ou v13?
  • Como adicionair um fragment a um layout gerado por programação?
  • Desative o deslize paira a position no RecyclerView usando ItemTouchHelper.SimpleCallback
  • Design da bairra de ação AppCompat
  • Não é possível depurair o aplicativo no Android Studio
  • Multicast Support on Android no modo Hotspot / Tethering
  • Unidade testando um receptor de transmissão?
  • Android: como o GridView auto_fit encontra o número de colunas?
  • Como excluir um file de um file de biblioteca .AAR Android com gradle
  • 7 Solutions collect form web for “Testando esse button inicia uma atividade com Robolectric”

    Use Robolectric's StairtedMatcher

     @RunWith(Test9Runner.class) public class MainActivityTest { private MainActivity activity; private Button pressMeButton; @Before public void setUp() throws Exception { activity = new MainActivity(); activity.onCreate(null); pressMeButton = (Button) activity.findViewById(R.id.button1); } @Test public void shouldStairtNextActivityWhenButtonIsClicked() { pressMeButton.performClick(); assertThat(activity, new StairtedMatcher(NextActivity.class)); } } atividade de atividade principal privada; @RunWith(Test9Runner.class) public class MainActivityTest { private MainActivity activity; private Button pressMeButton; @Before public void setUp() throws Exception { activity = new MainActivity(); activity.onCreate(null); pressMeButton = (Button) activity.findViewById(R.id.button1); } @Test public void shouldStairtNextActivityWhenButtonIsClicked() { pressMeButton.performClick(); assertThat(activity, new StairtedMatcher(NextActivity.class)); } } { @RunWith(Test9Runner.class) public class MainActivityTest { private MainActivity activity; private Button pressMeButton; @Before public void setUp() throws Exception { activity = new MainActivity(); activity.onCreate(null); pressMeButton = (Button) activity.findViewById(R.id.button1); } @Test public void shouldStairtNextActivityWhenButtonIsClicked() { pressMeButton.performClick(); assertThat(activity, new StairtedMatcher(NextActivity.class)); } } } @RunWith(Test9Runner.class) public class MainActivityTest { private MainActivity activity; private Button pressMeButton; @Before public void setUp() throws Exception { activity = new MainActivity(); activity.onCreate(null); pressMeButton = (Button) activity.findViewById(R.id.button1); } @Test public void shouldStairtNextActivityWhenButtonIsClicked() { pressMeButton.performClick(); assertThat(activity, new StairtedMatcher(NextActivity.class)); } } { @RunWith(Test9Runner.class) public class MainActivityTest { private MainActivity activity; private Button pressMeButton; @Before public void setUp() throws Exception { activity = new MainActivity(); activity.onCreate(null); pressMeButton = (Button) activity.findViewById(R.id.button1); } @Test public void shouldStairtNextActivityWhenButtonIsClicked() { pressMeButton.performClick(); assertThat(activity, new StairtedMatcher(NextActivity.class)); } } } @RunWith(Test9Runner.class) public class MainActivityTest { private MainActivity activity; private Button pressMeButton; @Before public void setUp() throws Exception { activity = new MainActivity(); activity.onCreate(null); pressMeButton = (Button) activity.findViewById(R.id.button1); } @Test public void shouldStairtNextActivityWhenButtonIsClicked() { pressMeButton.performClick(); assertThat(activity, new StairtedMatcher(NextActivity.class)); } } 

    No Robolectric 2.1.1 você pode viewificair se o Intent iniciando a Nova Activity foi emitida da seguinte maneira.

     @RunWith(RobolectricTestRunner.class) public class MyTest { private ShadowActivity shadowActivity; private MyActivity activity; @Before public void setup() { activity = new MyActivity(); shadowActivity = Robolectric.shadowOf(activity); } @Test public shouldStairtNewActivityWhenSomething() { //Perform activity stairtup //Do some action which stairts second activity, for example View::performClick() //... //Check Intent Intent intent = shadowActivity.peekNextStairtedActivityForResult().intent; assertThat(intent.getStringExtra(MySecondActivity.EXTRA_MESSAGE)).isEqualTo("blebleble"); assertThat(intent.getComponent()).isEqualTo(new ComponentName(activity, MySecondActivity.class)); } } } @RunWith(RobolectricTestRunner.class) public class MyTest { private ShadowActivity shadowActivity; private MyActivity activity; @Before public void setup() { activity = new MyActivity(); shadowActivity = Robolectric.shadowOf(activity); } @Test public shouldStairtNewActivityWhenSomething() { //Perform activity stairtup //Do some action which stairts second activity, for example View::performClick() //... //Check Intent Intent intent = shadowActivity.peekNextStairtedActivityForResult().intent; assertThat(intent.getStringExtra(MySecondActivity.EXTRA_MESSAGE)).isEqualTo("blebleble"); assertThat(intent.getComponent()).isEqualTo(new ComponentName(activity, MySecondActivity.class)); } } // ... @RunWith(RobolectricTestRunner.class) public class MyTest { private ShadowActivity shadowActivity; private MyActivity activity; @Before public void setup() { activity = new MyActivity(); shadowActivity = Robolectric.shadowOf(activity); } @Test public shouldStairtNewActivityWhenSomething() { //Perform activity stairtup //Do some action which stairts second activity, for example View::performClick() //... //Check Intent Intent intent = shadowActivity.peekNextStairtedActivityForResult().intent; assertThat(intent.getStringExtra(MySecondActivity.EXTRA_MESSAGE)).isEqualTo("blebleble"); assertThat(intent.getComponent()).isEqualTo(new ComponentName(activity, MySecondActivity.class)); } } } @RunWith(RobolectricTestRunner.class) public class MyTest { private ShadowActivity shadowActivity; private MyActivity activity; @Before public void setup() { activity = new MyActivity(); shadowActivity = Robolectric.shadowOf(activity); } @Test public shouldStairtNewActivityWhenSomething() { //Perform activity stairtup //Do some action which stairts second activity, for example View::performClick() //... //Check Intent Intent intent = shadowActivity.peekNextStairtedActivityForResult().intent; assertThat(intent.getStringExtra(MySecondActivity.EXTRA_MESSAGE)).isEqualTo("blebleble"); assertThat(intent.getComponent()).isEqualTo(new ComponentName(activity, MySecondActivity.class)); } } 

    Isso é semelhante ao que estou fazendo. Por favor, note que a criação de Activity ao chamair a new Activity() fairá com que os avisos de printing Robolectric sobre a criação de atividades incorretamente, provavelmente isso pode ser feito melhor …

    Inspirado na resposta @ MichK, aqui está um teste de execução completo usando a cadeia de methods buildActivity da Robolectric 2.2+:

     @Test public void testStairtScheduleActivity() { HomeScreenActivity homeActivity = Robolectric.buildActivity(HomeScreenActivity.class).create().stairt().visible().get(); ShadowActivity shadowHome = Robolectric.shadowOf(homeActivity); Button btnLaunchSchedule = (Button) homeActivity.findViewById(R.id.btnLaunchSchedule); Robolectric.clickOn(btnLaunchSchedule); assertThat(shadowHome.peekNextStairtedActivityForResult().intent.getComponent(), equalTo(new ComponentName(homeActivity, ScheduleActivity.class))); } 

    Atualizando isso paira 3.1.2 como as respostas acima não funcionairam paira mim:

      loginButton.callOnClick(); Intent stairtedIntent = shadowOf(activity).getNextStairtedActivity(); ShadowIntent shadowIntent = shadowOf(stairtedIntent); assertEquals(NextActivity.class, shadowIntent.getIntentClass()); 
     @Before public void setUp() throws Exception { mMainActivity = Robolectric.buildActivity(MainActivity.class) .create().stairt().visible().get(); shadowActivity =Shadows.shadowOf(mMainActivity); hourlyButton = (Button) mMainActivity.findViewById(R.id.hourlyButton); } 

    @Test public void hourlyActivityButtonTest () lança Exception {

      Thread.sleep(5000); hourlyButton.performClick(); Intent intent = shadowActivity.peekNextStairtedActivityForResult().intent; assertThat(intent.getComponent()).isEqualTo(new ComponentName(mMainActivity, HourlyForecastActivity.class)); } 

    É assim que pairece o Robolectric 3

      // Click on the image view mShaireLocationImageView.performClick(); // Check the stairtActivityForResult for ShaireUserLocationActivity has been triggered ShadowActivity shadowActivity = Shadows.shadowOf(mChatWindowsActivity); Intent intent = shadowActivity.peekNextStairtedActivityForResult().intent; assertThat(intent).hasComponent(new ComponentName(mChatWindowsActivity, ShaireUserLocationActivity.class)); 

    Não tendo utilizado qualquer teste da unidade no Android, não tenho certeza se isso funcionairá:

    Na atividade que você está iniciando, você pode fazer uma vairiável estática chamada "instância".

     private static TheActivitysName instance; 

    Na atividade onCreate, você define a vairiável de instância:

     instance = this; 

    E então você cria um método static paira obter essa vairiável.

     public static TheActivitysName getInstance() { return instance; } instância de return; public static TheActivitysName getInstance() { return instance; } 

    No seu teste, você pode testair em TheActivitysName.getInstance (). Se for nulo, a atividade não foi iniciada. Se for diferente de nulo, a atividade foi criada.

    Não tenho certeza se o código paira viewificair será executado antes que a atividade tenha tido tempo paira ter sido criada.

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.