Creating Generics and Testsuites – Selenium Tutorial #22

In the previous tutorial, we started off with the representation of the sample project hierarchy and various framework components. We also discussed about the data source – “excels” used to store the test data and their excel manipulations. We also discussed about the new strategies and resources to mature our framework.

Now we are moving ahead with advanced topics in this Selenium Training Series. In this session, we would take the opportunity to discuss two important concepts that plays an important role to mature the framework. We would discuss the concept of Generics and reusability aspects. We would also discuss about creation and significance of Test suite.

For better understanding we would accompany the concepts with adequate examples and sample code.

Generics

By the literal notion, a generic is something that can act as a descriptive of an entire group or classes.

While automating applications, we come across various end to end scenarios. An end to end scenario may consist of several trivial functionality. Thus, many of these functionality can act as common functionality to more than one test script with slight or almost no modifications.

Hence, it is advisable to create a generic class consisting of methods that can be claimed as common and can be shared among multiple test scripts instead of implementing the same code again and again for multiple test scripts.

Take a note that generics also introduce the power of reusability in our framework. Reusability reduces time taken for code, errors, bugs, maintenance etc. exceptionally.

Type of Generics

#1) Application Specific

The meager functionality belonging to application under test can become a part of the Application Specific generics. Take the Login Functionality for instance. Login is one such functionality that can be a fragment of almost all the test scripts. Thus, instead of writing the login code all over again in the test scripts, we would create a common method in the generic class and call it wherever needed.

#2) Framework Specific

Aside from Application specific generics, we may have common methods which do not directly relate with the application under test but are part of the chosen framework. Consider an Excel reading functionality when we have employed Test Data Driven Framework. It would make no sense if we would write the code for reading excels again and again in all the test scripts. Therefore, we induce the code once in the generic class and make a call to it whenever required.

Creation of Generic Class

User is leveraged to create as many generic classes as he/she desires based on the modularity infused.

Let us understand the concept of generic by creating one.

Step 1: Create a new java class “CommonMethods.java” that would act as a generic class consisting of common methods preferably in the package other than where test scripts reside.

Step 2: The next step is to copy and paste the below code in the “CommonMethods.java” generic class. Number of common methods can be implemented inside the periphery of this class. Below is the code snippet for login functionality.

/**
* Login the Test application
*
* @param username
* @param password
*/
public void login(String username, String password) {
try {
// Enter User Name
WebElement userName = driver.findElement(By.id("loginID"));
userName.clear();
userName.sendKeys(username);
// Enter Password
WebElement passWord = driver.findElement(By.id("Password"));
passWord.clear();
passWord.sendKeys(password);
// Click on the Sign In Button
WebElement signin = driver.findElement(By.id("SignIn_button"));
signin.click();
driver.manage().window().maximize();
} catch (Exception e) {
e.printStackTrace();
}
}

Take a note that the aforementioned method is a parameterized method. Thus, the same method can be used to test the login functionality with different sets of test data.

Step 3: The next step is to call the common method within the test script. The process is a two step process. First we create the instance of the generic class within the test class and then we call the common method on the created instance by passing the required arguments. In the code fragment below, we created an instance of “TestScript1.java” class and called the login () method to login the application.

// Create Object of the generic class
toolsObj = new Tools();
// Login the test application by calling the common method
preTestObj.login(“username”, “password”);

Take a mention that the above code can be placed anywhere inside the test class. User can place the code in the setup () method or in the test () method.

Testsuite

Test suite is an assortment of more than one test script grouped together for execution purpose. Thus, test suite executes the number of specified test scripts unattended. Test suite has the capability to cite the test scripts to be executed automatically; all that is required from the user is to mark an entry each for the individual test script within the test suite. The entry is supposed to be the “class name” of the test script with “.class” extension or simply the compiled form of our java class.

Below is the sample Test suite created in java. Take a note that Test suite is a java based class that belongs to the family of JUnit. Thus, you may encounter several JUnit annotations in the code.

Selenium test suite


Code Snippet

package com.axway.webliv.tests;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runner.notification.Failure;
import org.junit.runners.Suite;
import com.axway.webliv.tests.MetaData.*;

@RunWith(Suite.class)
@Suite.SuiteClasses({ 

       ChangeStatusBinarySphereTest.class,
       ChangeStatusRestrictionTest.class,
       ChangeStatusDocSphereTest.class,
      })

public class TestSuite {
       /**
        * Setup method to set system properties
        */
       @BeforeClass
       public static void Setup() {
       }
       /**
        * @param args
        */
       public static void main(String[] args) {
              Result result = JUnitCore.runClasses(TestSuite.class);
              System.out.println("TEST CASES RUN: " + result.getRunCount());
              System.out.println("TEST CASES FAILED: " + result.getFailureCount());
              for (Failure failure : result.getFailures()) {
                     System.out.println("\nTEST NAME: " + failure.getTestHeader());
                     System.out.println("\nERROR: " + failure.getMessage() + "\n");
                     System.out.println(failure.getTrace());
                     System.exit(1);
              }
       }
       /**
        * Report test results
        */
       @AfterClass
       public static void TearDown() {         
       }
}

Code Walk-Through

A test suite is none other than a simple JUnit class having setup() and teardown() methods; the one’s we discussed at length in our preceding tutorials. The only remarkable difference lies in its competence to execute more than one test script in a single go.

Import Statements

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runner.notification.Failure;
import org.junit.runners.Suite;

The above import statements are embedded in the class to be able to use various annotations provided by the JUnit.

import org.junit.runner.JUnitCore;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

The above statements possess the underlying architecture to execute the test suite consisting of multiple test classes.

import org.junit.runner.Result;

The import statement allows the user to store the test execution statuses and their manipulations.

import org.junit.AfterClass;
import org.junit.BeforeClass;

These import statements are used to identify and annotate setup() and teardown() methods. The setup() method annotated with BeforeClass instructs the program control to execute the method before each of the test script execution. Like setup(), teardown() method annotated with AfterClass tells the program control to execute the method after each of the test script execution.

Class Entry

@RunWith(Suite.<strong>class</strong>)
@Suite.SuiteClasses({
       ChangeStatusBinarySphereTest.<strong>class</strong>,
       ChangeStatusRestrictionTest.<strong>class</strong>,
       ChangeStatusDocSphereTest.<strong>class</strong>,
       })

This section of the class allows the user to mark the entries of the test script to be executed in the next run. Remember the entries are marked with “.class” extension i.e. in their compiled formats.

Execution – main ()

public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestSuite.class);
System.out.println("TEST CASES RUN: " + result.getRunCount());
System.out.println("TEST CASES FAILED: " + result.getFailureCount());
for (Failure failure : result.getFailures()) {
System.out.println("\nTEST NAME: " + failure.getTestHeader());
System.out.println("\nERROR: " + failure.getMessage() + "\n");
System.out.println(failure.getTrace());
System.exit(1);
}
}

This part of the code deals with the execution. The program execution always initiates from the main().

The runClasses method of JUnitCore class is used to execute the test suite. The “Result class” and its methods are used to determine the execution status in terms of Passed and Failed test cases.

Thus, user is leveraged to play around with the test suite class to be able to suffice his/her requirements.

Conclusion

In this tutorial, we tried to make you acquainted with the concept of generics and common methods. We also discussed the benefits we get out generics like reusability. We also shared the practical approaches towards creation of generics and their accessibility.

Here are the cruxes of this article:

  • Generic is something that can act as a descriptive of an entire group or classes. Generic in our framework is a class that is solely consists of methods those can be shared across multiple test classes.
  • Generics can be classified into two categories:
    • Application Specific
    • Framework Specific
  • A simple java class can be created to act as a Generic. Number of common methods can be implemented inside the generic class. These methods can be parameterized methods.
  • The common methods can be accessed by calling them on the instance of generic class within the test scripts.
  • Test suite is an assortment of more than one test script grouped together for execution purpose. Thus, test suite executes the number of specified test scripts unattended.
  • A test suite is none other than a simple JUnit class having setup() and teardown() methods; the one’s we discussed at length in our preceding tutorials. The only remarkable difference lies in its competence to execute more than one test script in a single go.

Next Tutorial #23: Going forward in the next tutorial we would study about yet another tool for automating the entire build process. Thus, we would discuss “Ant” in the next tutorial at length. We would discuss about the need of an hour to use a build tool in Test Automation. We would slide down to the deeper sections where we would define the project dependencies and create build.xml file.

Note for the Readers – As we have already covered the major part of framework in this and the previous few tutorials, readers can start exercising these concepts and can come up with their own customized framework.




Recommended reading

8 comments ↓

#1 Rohit

can we create test suite in Selenium IDE?

#2 Shruti Shrivastava

@Rohit

Yes, we can create testsuite in Selenium IDE.
Please refer the Selenium IDE tutorial for the same.

#3 Amit

For Example : we have 1000+ testcases to do aumoted so we have to write 1000++ times drier.findelement now I want to make one general method so whenever it require to write driver.findelement we can ingnor it y writing just that general method name

Can you suggest me how to do it ??

#4 Nilan

Thanks for this tutorial. It really helped me a lot.

Got one question while trying to build the framework and the test scripts.

How can we pass the driver instance in the test script (created in Setup() method) to the application method (say login) in CommonMethods class. Should we include a third parameter to the login method containing driver? What would be the best way to do this?

thanks.

#5 Gaurav Khurana

Thanks for this. But last 3 tutorials 20/21/22 i am not satisfied with the way these tutorials are covered in a small length.

Its a request if you can cover these topics at length as they are the way things are being used in project.

Once we achieve this, we may learn other things. please elaborate these tutorials

#6 rohit

i need to report in multiply java method result

#7 amit

If we create a java method and write down whole code inside the method, then can we called this method as test suit ?

#8 Ashok

Not satisfied with this tutorial.. need more explanation.. the first 15 tutorials are great.. but after that, it is not good.. please provide the full detailed tutorial

Leave a Comment