How to Write and Run First Test Case in Android Studio?

How to Write and Run First Test Case in Android Studio?


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.

Perquisite –

  • Create an Android Studio Project
  • Configure TestNG Framework.
  • Configure Espresso Tool


Steps for Writing Test Cases –

      • Go to app -> src ->androidTest -> Java Android Studio


      • Right click on the package name


      • Go to New -> Java Class and click
      • Enter File Name and Click on Ok.
      • “Now your java class is ready.>

Now we will write a simple code as per given below

Test Case Explanation –

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.

Running Test Case –

        • For Android Studio Version Less than 2.1
          • Click on Build Variants
      • Select Android Instrumentation Tests
      • Right click on class name and click on Run
      • For Android Studio Versions More than 2.1
        1. Right click on class name and click on Run

bodrum escort - eskişehir esc - mersin escort - mersin escort bayan - mersin esc