Testing that button starts an Activity with Robolectric

后端 未结 8 842
眼角桃花
眼角桃花 2020-12-24 11:25

Hi I have the following code:

@RunWith(Test9Runner.class)
public class MainActivityTest 
{
    private MainActivity activity;
    private Button pressMeButto         


        
相关标签:
8条回答
  • 2020-12-24 11:55

    Having not used any of the unit testing in android, i am not sure if this will work:

    In the activity you are starting, you could make a static variable called "instance".

    private static TheActivitysName instance;
    

    In the activity onCreate you set the instance variable:

    instance = this;
    

    And then you create a static method to get this variable.

    public static TheActivitysName getInstance() {
        return instance;
    }
    

    In your test, you can then test on TheActivitysName.getInstance(). If it is null, then the activity has not been started. If it is different from null, then the activity has been created.

    I'm not sure if code to check will be executed before the activity has had time to been created though.

    0 讨论(0)
  • 2020-12-24 11:57

    In Robolectric 2.1.1 you can verify if Intent starting new Activity was emitted in following way.

    @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 shouldStartNewActivityWhenSomething() {
        //Perform activity startup
        //Do some action which starts second activity, for example View::performClick()
        //...
        //Check Intent
        Intent intent = shadowActivity.peekNextStartedActivityForResult().intent;
        assertThat(intent.getStringExtra(MySecondActivity.EXTRA_MESSAGE)).isEqualTo("blebleble");
        assertThat(intent.getComponent()).isEqualTo(new ComponentName(activity, MySecondActivity.class));
      }
    }
    

    This is similar to what I am doing. Please note that creating Activity by calling new Activity() will make Robolectric print warnings about creating activity improperly, this probably can be done better...

    0 讨论(0)
提交回复
热议问题