So far we have learnt on creating our Android Studio project and overview of Junit and TestNG testing framework. In this Tutorial, we will write our first test case and run it. It sounds exciting but before that we need to decide a testing tool which we want to use for writing testing Framework.
We have many famous testing tools in market like Appium, Robotium , Espresso etc. Espresso is an open source framework provided by Android Studio so let use that to write our first test case.
The main purpose of this tutorial is to learn to write and run test case in Android Studio so we will focus on this and not on testing tools. We will learn about testing tools in future posts.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
@RunWith(AndroidJUnit4.class) @LargeTest public class EspressoTest1 extends ActivityInstrumentationTestCase2<MainActivity>{ public EspressoTest1() { super(MainActivity.class); } @Before public void setUp() throws Exception { super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); } @Test public void test1ChatId() { getActivity(); onView(withId(R.id.helloworld)).check(matches(isDisplayed())); } @After public void tearDown() throws Exception { super.tearDown(); } } |
1. The class uses two annotations @LargeTest and @Runwith these two annotations are used to specify the behavior for our TestClass.
2. The class extends AcitivtyInstrumentationTestCase2 class with launch activity as MainActivity which we want to test in this example.
3. @Before and @After is annotations and used to specify which method should be executed before each test case and which method should be executed after completion of each test case.
4.@Test annotation is added for each test case method.
5. In the below test case the getAcitivity() launches our Main Activity.
6. onView() is used to select a view for testing and withId() is used to locate the UI element and rest is used to check whether the particular element is displayed or not.