Crashes and ANR's Mobile Testing

Crashes and ANR’s

Crashes:

A crash occurs when a mobile application unexpectedly terminates and stops functioning due to an unhandled exception or error in the code. When a crash happens, the app is forcibly closed by the operating system to prevent it from causing further issues or affecting the device’s stability. Crashes are typically caused by programming errors, bugs, or unexpected conditions that the app’s code fails to handle properly.

Common Causes of Crashes:

a. Null Pointer Exception: When the app attempts to access an object or variable that is set to null, resulting in a runtime error.

b. Array Index Out of Bounds: Occurs when the app tries to access an element in an array with an invalid index, causing the app to crash.

c. Divide By Zero: If the app performs a division operation with zero as the divisor, it leads to an arithmetic exception and causes a crash.

d. Out of Memory: When the app exhausts its available memory due to memory leaks or excessive memory usage, it may crash.

e. Concurrent Modification: If multiple threads try to modify the same data structure simultaneously without proper synchronization, it can lead to crashes.

How Crashes are Handled:

When an app crashes, the operating system generates a crash report or stack trace, which includes information about the state of the app at the time of the crash. Developers can use crash reporting tools or logging mechanisms to collect crash reports and identify the root cause of the crash. These crash reports help developers identify and fix bugs in their code to prevent future crashes.

ANRs (Application Not Responding):

ANR stands for “Application Not Responding,” and it occurs when the user interface (UI) of the mobile application becomes unresponsive for a significant period. When the main thread of the app is busy performing long-running operations or blocking UI updates, it is unable to respond to user interactions or system events, leading to an ANR.

Common Causes of ANRs:

a. Long-Running Operations: When the app performs time-consuming tasks on the main thread, such as complex computations or data processing, the UI becomes unresponsive.

b. Network Operations on Main Thread: Performing network requests on the main thread can cause ANRs, especially if the network connection is slow or experiences delays.

c. Database Operations on Main Thread: When the app executes database queries or data manipulation on the main thread, it can block UI updates and lead to ANRs.

d. Synchronization Issues: Poorly synchronized code or deadlocks can cause the main thread to become stuck, resulting in ANRs.

How ANRs are Handled:

When an ANR occurs, the Android system detects the unresponsiveness and displays a dialog to the user, indicating that the app is not responding. The dialog gives the user the option to wait for the app to respond or force-close the app. ANRs are typically logged, and developers can use the information to analyze the problematic code sections and optimize long-running operations.

Preventing Crashes and ANRs:

To prevent crashes and ANRs in mobile applications, developers should follow best practices such as:

  • Handling exceptions properly by using try-catch blocks to handle potential errors.
  • Offloading long-running tasks to background threads to keep the main thread responsive.
  • Using asynchronous programming techniques for network requests and database operations.
  • Regularly testing the app and monitoring for crashes and ANRs using crash reporting tools.
  • Optimizing memory usage and handling resource-intensive operations efficiently.

By addressing and resolving crashes and ANRs, developers can create stable and responsive mobile applications, providing a positive user experience for their users.

Difference Between Crashes and ANR’s:

Crash and ANR (Application Not Responding) are two different types of issues that can occur in mobile applications, and they have distinct characteristics and implications:

  1. Crash:
    • A crash occurs when the mobile application abruptly stops working and exits unexpectedly. It is usually caused by an unhandled exception or error in the app’s code, resulting in the app terminating abruptly.
    • When a crash happens, the app may display an error message to the user, and the system may generate a crash report or stack trace, providing information about the cause of the crash.
    • Common causes of crashes include null pointer exceptions, array index out of bounds, and other runtime errors.
  2. ANR (Application Not Responding):
    • ANR stands for Application Not Responding, and it occurs when the user interface (UI) of the mobile application becomes unresponsive for a significant period, typically around 5 seconds or more.
    • ANRs happen when the main thread of the app is busy performing long-running tasks (e.g., complex computations, network operations) without releasing control to the system’s event loop to process user input or handle UI updates.
    • When an ANR occurs, the Android system detects the unresponsiveness and displays a dialog to the user, stating that the app is not responding and giving the option to wait or force-close the app.

In summary, the main difference between a crash and an ANR is that a crash is an unexpected termination of the app due to a fatal error in the code, while an ANR occurs when the app becomes unresponsive for a certain period due to long-running operations on the main thread. Both issues are undesirable for mobile applications, as they can lead to a negative user experience and impact the app’s reputation. Developers should regularly test their apps, handle exceptions properly, and optimize long-running tasks to minimize the occurrence of crashes and ANRs.

Mobile Testing

Functional and Non Functional Testing in Mobile Application

Functional Testing in Mobile APp

Functional testing in mobile application testing is the process of evaluating the app’s functionality to ensure that it works as intended and meets the specified requirements. It focuses on verifying whether the app’s features and functionalities perform as expected and deliver the desired outcomes. Functional testing ensures that the app functions correctly across different devices, operating systems, and user scenarios. Here are key aspects and approaches to functional testing in mobile applications:

  1. Functional Test Scenarios:
    • Identify and design test scenarios that cover various aspects of the app’s functionality.
    • Test scenarios should represent real-world user interactions and cover positive, negative, and edge cases.
  2. User Interface (UI) Testing:
    • Verify that the app’s user interface elements are correctly displayed and responsive.
    • Check the alignment, layout, and visual elements on different devices with varying screen sizes and resolutions.
  3. Navigation Testing:
    • Test the app’s navigation flow to ensure smooth transitions between screens and modules.
    • Validate that back, home, and other navigation buttons function as expected.
  4. User Input and Output Testing:
    • Validate user input fields, buttons, and other interactive elements for accurate input and output responses.
    • Test form submissions, data entry, and validation of user inputs.
  5. Functional Integration Testing:
    • Test interactions between different app components, such as activities, services, and external APIs.
    • Verify that integrated features work seamlessly and exchange data correctly.
  6. Database and Backend Testing:
    • Validate data storage and retrieval in the app’s local database or backend server.
    • Test CRUD (Create, Read, Update, Delete) operations for data integrity.
  7. Feature Testing:
    • Test each app feature independently and in combination with other features.
    • Ensure that all features work as per their requirements and do not conflict with each other.
  8. Offline Functionality Testing:
    • Test the app’s behavior when there is no internet connection.
    • Verify that the app provides appropriate offline support and data synchronization when the connection is restored.
  9. Device-Specific Testing:
    • Perform testing on various devices and screen sizes to ensure compatibility and consistent functionality.
    • Test on different operating system versions to verify backward compatibility.
  10. Localization Testing:
    • Validate the app’s functionality with different languages and locales.
    • Ensure that localized content and user interfaces are accurate and displayed correctly.
  11. Accessibility Testing:
    • Check the app’s accessibility features for users with disabilities, such as voiceover, large text, and contrast adjustments.

Functional testing is a critical part of mobile application testing as it ensures that the app meets the user’s expectations and performs its intended functions without errors or glitches. By conducting comprehensive functional testing, developers can identify and address issues early in the development process, leading to a higher quality and more user-friendly mobile app.

Non Functional Testing in Mobile Application

Non-functional testing in mobile application testing focuses on evaluating aspects of the app’s performance, usability, security, and other quality attributes that are not directly related to its functionality. These tests assess how well the app performs under different conditions and how it meets the non-functional requirements and user expectations. Here are key aspects and approaches to non-functional testing in mobile applications:

  1. Performance Testing:
    • Load Testing: Assess the app’s performance under various user loads to ensure it can handle concurrent users without significant slowdowns or crashes.
    • Stress Testing: Test the app’s stability and performance under extreme conditions, such as high load or low network connectivity.
    • Responsiveness Testing: Measure the app’s response time to user actions, ensuring quick and smooth interactions.
  2. Usability Testing:
    • User Experience (UX) Testing: Evaluate the app’s user interface and interactions to ensure they are intuitive, user-friendly, and visually appealing.
    • Navigation Testing: Verify that users can navigate through the app efficiently and without confusion.
    • User Feedback Collection: Gather feedback from real users to identify usability issues and areas for improvement.
  3. Compatibility Testing:
    • Device Compatibility: Test the app on different devices with various screen sizes, resolutions, hardware configurations, and operating system versions.
    • OS Compatibility: Verify the app’s compatibility with different versions of the target operating systems.
  4. Security Testing:
    • Vulnerability Testing: Identify and address security vulnerabilities, such as data breaches, insecure data storage, and inadequate authentication mechanisms.
    • Authorization and Authentication Testing: Verify that the app enforces proper user authentication and authorization controls.
  5. Network Connectivity Testing:
    • Test the app’s behavior under varying network conditions, including Wi-Fi, 3G, 4G, and offline scenarios.
    • Validate the app’s handling of network interruptions and data synchronization.
  6. Battery and Resource Usage Testing:
    • Evaluate the app’s impact on the device’s battery life and resource consumption (CPU, memory).
    • Optimize the app to minimize battery drain and resource usage.
  7. Install/Uninstall Testing:
    • Verify that the app installs and uninstalls correctly without leaving behind any residual files or data.
  8. Compliance Testing:
    • Check the app’s compliance with relevant industry standards, regulations, and guidelines.
  9. Localization and Internationalization Testing:
    • Ensure that the app functions correctly with different languages, date formats, and regional settings.
  10. Recovery Testing:
    • Test the app’s ability to recover from crashes, network failures, and other unexpected events.

Non-functional testing is crucial for delivering a high-quality mobile app that not only works as intended but also meets user expectations in terms of performance, security, usability, and overall user experience. By conducting comprehensive non-functional testing, developers can identify and address potential issues that may impact the app’s usability and reliability in real-world scenarios.

Mobile Testing

What is Manifest.xml in Android App?

The manifest file, also known as the “AndroidManifest.xml” file, is an essential configuration file in Android app development. It is a static XML file that provides essential information about the Android app to the Android operating system. Every Android app must include a manifest file in its root directory.

The AndroidManifest.xml file contains critical metadata and instructions that the Android operating system uses to understand and interact with the app. It serves several important purposes:

  1. App Information: The manifest file contains information about the app, such as its package name, version code, version name, app name, and icon. This information helps the operating system identify and manage the app.
  2. Components Declaration: The manifest file declares all the components of the app, including activities, services, broadcast receivers, and content providers. Each component is defined with its name, type, and intent filters to indicate which actions it can handle.
  3. Permissions Declaration: The manifest file lists the permissions required by the app to access specific features or data on the device. These permissions must be explicitly declared, and users are informed about them during app installation.
  4. App Configuration: The manifest file includes configuration settings for the app, such as supported screen orientations, minimum and target SDK versions, hardware requirements, and more.
  5. Intent Filters: Intent filters in the manifest file specify the types of intents (messages) that the app can handle. For example, an activity may have an intent filter to handle the “VIEW” action for specific data types, allowing the app to be launched when certain URLs or files are clicked.
  6. App Components Relationships: The manifest file defines the relationships between different app components, such as which activity is the main entry point of the app.

The AndroidManifest.xml file plays a crucial role in the Android app’s lifecycle and defines the app’s identity, capabilities, and interactions with the Android system and other apps. It acts as a contract between the app and the operating system, allowing the system to manage app installations, permissions, and user interactions effectively. Developers must ensure that the manifest file is correctly configured and contains all the necessary information and declarations required for the app to function correctly on Android devices.

Mobile Testing

What is Info.plist in IOS App?

Info.plist is a configuration file used in iOS and macOS app development. It is an XML property list file that contains essential metadata and configuration details about the app. The Info.plist file is a crucial part of every iOS and macOS app bundle, and it is automatically created when you create a new project in Xcode.

In iOS development, the Info.plist file contains information about the app’s identity, version, supported devices, required permissions, app icons, and launch screen configuration, among other details. It is used by the iOS operating system to understand and manage the app during installation and runtime.

Key contents of the Info.plist file in iOS app development include:

  1. Bundle Identifier: A unique string that identifies the app, typically in reverse domain name notation (e.g., com.example.appname).
  2. App Version and Build Number: Version number and build number of the app for tracking different app releases.
  3. Supported Device Orientations: Specifies the supported interface orientations (portrait, landscape) for the app.
  4. Required Device Capabilities: Describes the hardware features and capabilities required by the app (e.g., camera, accelerometer).
  5. App Icons: The names of the app’s icon files to be used on the home screen and in the App Store.
  6. Launch Screen Configuration: Specifies the initial screen or storyboard to be shown when the app is launched.
  7. Supported iOS Versions: The minimum and maximum iOS versions supported by the app.
  8. Required Permissions: Declares the app’s permissions for accessing sensitive data, hardware, or system resources.

In macOS app development, the Info.plist file serves a similar purpose and includes configuration information specific to macOS apps.

The Info.plist file is an integral part of the app bundle and is automatically generated and updated by Xcode as developers modify the app’s settings and configurations. It ensures that the app is correctly recognized and managed by the operating system and provides essential information for app reviewers and users in the App Store. Developers should be cautious when editing the Info.plist file manually to avoid errors that could affect the app’s functionality and compatibility.

Automation Testing

TestNG Tutorial | What is Annotations & Framework in…

What is TestNG?

TestNG is an automation testing framework in which NG stands for “Next Generation”. TestNG is inspired by JUnit which uses the annotations (@). TestNG overcomes the disadvantages of JUnit and is designed to make end-to-end testing easy.

Using TestNG, you can generate a proper report, and you can easily come to know how many test cases are passed, failed, and skipped. You can execute the failed test cases separately.

For example:

  • Suppose, you have five test cases, one method is written for each test case (Assume that the program is written using the main method without using testNG). When you run this program first, three methods are executed successfully, and the fourth method is failed. Then correct the errors present in the fourth method, now you want to run only fourth method because first three methods are anyway executed successfully. This is not possible without using TestNG.
  • The TestNG in Selenium provides an option, i.e., testng-failed.xml file in test-output folder. If you want to run only failed test cases means you run this XML file. It will execute only failed test cases.

Beside above concept, you will learn more on TestNG, like what are the Advantages of TestNG, how to create test methods using @test annotations, how to convert these classes into testing suite file and execute through the eclipse as well as from the command line.

Why Use TestNG with Selenium?

Default Selenium tests do not generate a proper format for the test results. Using TestNG in Selenium, we can generate test results.

Most Selenium users use this more than Junit because of its advantages. There are so many features of TestNG, but we will only focus on the most important ones that we can use in Selenium. Following are the key features of Selenium TestNG:

  • Generate the report in a proper format including a number of test cases runs, the number of test cases passed, the number of test cases failed, and the number of test cases skipped.
  • Multiple test cases can be grouped more easily by converting them into testng.xml file. In which you can make priorities which test case should be executed first.
  • The same test case can be executed multiple times without loops just by using keyword called ‘invocation count.’
  • Using testng, you can execute multiple test cases on multiple browsers, i.e., cross browser testing.
  • The TestNG framework can be easily integrated with tools like TestNG Maven, Jenkins, etc.
  • Annotations used in the testing are very easy to understand ex: @BeforeMethod, @AfterMethod, @BeforeTest, @AfterTest
  • WebDriver has no native mechanism for generating reports. TestNG can generate the report in a readable format like the one shown below.
  • TestNG simplifies the way the tests are coded. There is no more need for a static main method in our tests. The sequence of actions is regulated by easy-to-understand annotations that do not require methods to be static.
  • Uncaught exceptions are automatically handled by TestNG without terminating the test prematurely. These exceptions are reported as failed steps in the report.

Advantages of TestNG over JUnit

There are three major advantages of TestNG over JUnit:

  • Annotations are easier to understand
  • Test cases can be grouped more easily
  • Parallel testing is possible

What is Annotation in TestNG?

Annotations in TestNG are lines of code that can control how the method below them will be executed. They are always preceded by the @ symbol. A very early and quick TestNG Example is the one shown below.

TestNG Tutorial

Annotations will be discussed later in the section named “Annotations used in TestNG,”so it is perfectly ok if you do not understand the above TestNG Example just yet. It is just important to note for now that annotations in TestNG are easier to code and understand than in JUnit.

The ability to run tests in parallel is available in TestNG but not in JUnit, so the TestNG framework is more preferred for testers using Selenium Grid.

How to Write Test Cases in TestNG?

Step 1) Write your business logic and insert the TestNG annotations in your code.
Step 2) Add more information like class name, groups name, package name, etc
Step 3) Run the TestNG.

Create Test Case Using TestNG Annotations

Now, we will learn how to create our first test case using TestNG Annotations in Selenium:

Before we create a test case, we should first setup a new TestNG Project in Eclipse and name it as “FirstTestNGProject”.

Setting up a new TestNG Project

Step 1: Click File > New > Java Project

TestNG Tutorial

Step 2: Type “FirstTestNGProject” as the Project Name then click Next.

TestNG Tutorial

Step 3: We will now start to import the TestNG Libraries onto our project. Click on the “Libraries” tab, and then “Add Library…”

TestNG Tutorial

Step 4: On the Add Library dialog, choose “TestNG” and click Next.

TestNG Tutorial

Step 5: Click Finish.

TestNG Tutorial

You should notice that TestNG is included on the Libraries list.

TestNG Tutorial

Step 6: We will now add the JAR files that contain the Selenium API. These files are found in the Java client driver that we downloaded from https://www.selenium.dev/downloads/ when we were installing Selenium and Eclipse in the previous chapters.

TestNG Tutorial

Then, navigate to where you have placed the Selenium JAR files.

TestNG Tutorial

After adding the external JARs, your screen should look like this.

TestNG Tutorial

Step 7: Click Finish and verify that our FirstTestNGProject is visible on Eclipse’s Package Explorer window.

TestNG Tutorial

How to Create a New TestNG Test File

Now that we are done setting up our project in this TestNG tutorial, let us create a new TestNG file.

Step 1: Click on ‘src’ and Choose other.
Right-click on the “src” package folder then choose New > Other…

TestNG Tutorial

Step 2: Select TestNG class.
Click on the TestNG folder and select the “TestNG class” option. Click Next.

TestNG Tutorial

Step 3: Type the values.
Type the values indicated below on the appropriate input boxes and click Finish. Notice that we have named our Java file as “FirstTestNGFile”.

TestNG Tutorial

Step 4: Template Created.
Eclipse should automatically create the template for our TestNG file shown below.

TestNG Tutorial

Coding of our First TestNG Test Case Example

Let us now create our first Test Case that will check if Mercury Tours’ homepage is correct. Type your code as shown in the below TestNG Example:

package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.*;

public class firsttestngfile {
    public String baseUrl = "http://demo.guru99.com/test/newtours/";
    String driverPath = "C:\\geckodriver.exe";
    public WebDriver driver ; 
     
  @Test
  public void verifyHomepageTitle() {
       
      System.out.println("launching firefox browser"); 
      System.setProperty("webdriver.gecko.driver", driverPath);
      driver = new FirefoxDriver();
      driver.get(baseUrl);
      String expectedTitle = "Welcome: Mercury Tours";
      String actualTitle = driver.getTitle();
      Assert.assertEquals(actualTitle, expectedTitle);
      driver.close();
  }
}

Notice the following.

  • TestNG does not require you to have a main() method.
  • Methods need not be static.
  • We used the @Test annotation. @Test is used to tell that the method under it is a test case. In this case, we have set the verifyHomepageTitle() method to be our test case, so we placed an ‘@Test’ annotation above it.
  • Since we use annotations in TestNG, we needed to import the package org.testng.annotations.*.
  • We used the Assert class. The Assert class is used to conduct verification operations in TestNG. To use it, we need to import the org.testng.Assert package.

You may have multiple test cases (therefore, multiple @Test annotations) in a single TestNG file. This will be tackled in more detail later in the section “Annotations used in TestNG.”

Running the Test

To run the test, simply run the file in Eclipse as you normally do. Eclipse will provide two outputs – one in the Console window and the other on the TestNG Results window.

TestNG Tutorial
TestNG Tutorial

Checking reports created by TestNG

The Console window in Eclipse gives a text-based report of our test case results while the TestNG Results window gives us a graphical one.

TestNG Tutorial

Generating HTML Reports

TestNG has the ability to generate reports in HTML format.

Step 1: After running our FirstTestNGFile that we created in the previous section, right-click the project name (FirstTestNGProject) in the Project Explorer window then click on the “Refresh” option.

TestNG Tutorial

Step 2: Notice that a “test-output” folder was created. Expand it and look for an index.html file. This HTML file is a report of the results of the most recent test run.

TestNG Tutorial

Step 3: Double-click on that index.html file to open it within Eclipse’s built-in web browser. You can refresh this page any time after you rerun your test by simply pressing F5 just like in ordinary web browsers.

TestNG Tutorial

Annotations used in TestNG

In the previous section, you have been introduced to the @Test annotation. Now, we shall be studying more advanced annotations and their usages.

Multiple Test Cases

We can use multiple @Test annotations in a single TestNG file. By default, methods annotated by @Test are executed alphabetically. See the code below. Though the methods c_test, a_test, and b_test are not arranged alphabetically in the code, they will be executed as such.

TestNG Tutorial

Run this code and on the generated index.html page, click “Chronological view.”

TestNG Tutorial

Parameters

If you want the methods to be executed in a different order, use the parameter “priority”. Parameters are keywords that modify the annotation’s function.

  • Parameters require you to assign a value to them. You do.this by placing a “=” next to them, and then followed by the value.
  • Parameters are enclosed in a pair of parentheses which are placed right after the annotation like the code snippet shown below.
TestNG Tutorial

TestNG will execute the @Test annotation with the lowest priority value up to the largest. There is no need for your priority values to be consecutive.

TestNG Tutorial

The TestNG HTML report will confirm that the methods were executed based on the ascending value of priority.

TestNG Tutorial

Multiple Parameters

Aside from “priority,” @Test has another parameter called “alwaysRun” which can only be set to either “true” or “false.” To use two or more parameters in a single annotation, separate them with a comma such as the one shown below.

@Test(priority = 0, alwaysRun = true)
TestNG Tutorial

@BeforeTest and @AfterTest

@BeforeTestmethods under this annotation will be executed prior to the first test case in the TestNG file.
@AfterTestmethods under this annotation will be executed after all test cases in the TestNG file are executed.

Consider the code below.

package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.*;
public class firsttestngfile {
    public String baseUrl = "http://demo.guru99.com/test/newtours/";
    String driverPath = "C:\\geckodriver.exe";
    public WebDriver driver ; 
     
     @BeforeTest
      public void launchBrowser() {
          System.out.println("launching firefox browser"); 
          System.setProperty("webdriver.gecko.driver", driverPath);
          driver = new FirefoxDriver();
          driver.get(baseUrl);
      }
      @Test
      public void verifyHomepageTitle() {
          String expectedTitle = "Welcome: Mercury Tours";
          String actualTitle = driver.getTitle();
          Assert.assertEquals(actualTitle, expectedTitle);
     }
      @AfterTest
      public void terminateBrowser(){
          driver.close();
      }
}

Applying the logic presented by the table and the code above, we can predict that the sequence by which methods will be executed is:

  • 1st – launchBrowser()
  • 2nd – verifyHomepageTitle()
  • 3rd – terminateBrowser()

The placement of the annotation blocks can be interchanged without affecting the chronological order by which they will be executed.

Summary of TestNG Annotations

@BeforeSuite: The annotated method will be run before all tests in this suite have run.

@AfterSuite: The annotated method will be run after all tests in this suite have run.

@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.

@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.

@BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.

@AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.

@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.

@AfterClass: The annotated method will be run after all the test methods in the current class have been run.

@BeforeMethod: The annotated method will be run before each test method.

@AfterMethod: The annotated method will be run after each test method.

@Test: The annotated method is a part of a test case

Uncategorized

TestNG | How to set Test Priority in Selenium

TestNG is a Testing framework, that covers different types of test designs like a unit test, functional test, end to end test, UI test and integration test.

You can run a single or multiple test cases in your Testng code.

If test priority is not defined while, running multiple test cases, TestNG assigns all @Test a priority as zero(0).

Now, while running; lower priorities will be scheduled first.

How to set Priority in TestNG

We will be modifying the @Test annotation with Priority Parameter so that each test should run against to the priority assigned to them.

Now as you can see we have assigned the Priority to each test case means test case will the lower priority value will be executed first.

Priority in testNG in action

import org.openqa.selenium.By;			
import org.openqa.selenium.WebDriver;			
import org.openqa.selenium.firefox.FirefoxDriver;			
import org.testng.Assert;			
import org.testng.annotations.Test;			

public class Priority_In_testNG {		
    WebDriver driver;			

    // Method 1: Open Browser say Firefox			
    @Test (priority=1)		
    public void openBrowser() {				
        driver = new FirefoxDriver();				
    }		

    // Method 2: Launch Google.com			
    @Test (priority=2)		
    public void launchGoogle() {				
        driver.get("http://www.google.co.in");						
    }		

    // Method 3: Perform a search using "Facebook"			
    @Test (priority=3)		
    public void peformSeachAndClick1stLink() {				
        driver.findElement(By.xpath(".//*[@title='Search']")).sendKeys("Facebook");								
    }		

    // Method 4: Verify Google search page title.			
    @Test (priority=4)		
    public void FaceBookPageTitleVerification() throws Exception {				
        driver.findElement(By.xpath(".//*[@value='Search']")).click();						
        Thread.sleep(3000);		
        Assert.assertEquals(driver.getTitle().contains("Facebook - Google Search"), true);				
    }		
}		

Explanation of Code

After assigning priority to each testcases, run the above code using testNG as shown in Video-2 mentioned below.

Here, you can see that test cases are prioritized. Test case having lower priority are executed first i.e. now there is a sequential execution according to priority in the test cases. Hence, all test cases are passing now.

Note the console of eclipse:

Output :

PASSED: openBrowser
PASSED: launchGoogle
PASSED: peformSearchAndClick1stLink
PASSED: FaceBookPageTitleVerification