Wednesday 24 February 2016

Espresso Intent to Test Launch of Browser Activity



In my previous post we have seen how to use Espresso Intent to test dialer activity.We know sometimes our app launches activities which are outside our app liker dialer, camera or browser etc. In this post we will learn how to test browser activity using intent.

App Under Test -
Consider you have an app with a button "Click Here". Once you click it launches chrome browser and opens url www.google.com

Test Case Scenario -
Our test case is to click on the button and check the browser activity is launched and opens the right url.

Test Case-


import android.content.Intent;
import android.support.test.espresso.intent.rule.IntentsTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.intent.Intents.intended;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasAction;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasData;
import static android.support.test.espresso.intent.matcher.IntentMatchers.toPackage;
import static android.support.test.espresso.intent.matcher.UriMatchers.hasHost;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.equalTo;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@LargeTest
public class BrowserIntentTest {

    private static final String PACKAGE_NAME="com.android.chrome";
    @Rule
    public IntentsTestRule<MainActivity> mActivityRule = new IntentsTestRule<>(
            MainActivity.class);

    @Test
    public void test1()throws Exception
    {
            Thread.sleep(3000);
            onView(withId("Click Here")).perform(click());
            Thread.sleep(1000);
            intended(allOf(hasData(hasHost(equalTo("www.google.com"))),
                    hasAction(Intent.ACTION_VIEW),
                    toPackage(PACKAGE_NAME)));

    }
}

I hope this post helps you find your code coverage for your test suit :)
Please Share your feedback in comments section below and follow QA Automated to get latest post update.Happy Testing :-)

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Not a robust solution, because different phones may have different default browsers installed. E.g. if Samsung has Samsung Browser as a default, "com.sec.android.app.sbrowser" will be an expected package

    ReplyDelete