Automation QA Testing Course Content

Difference between Java and Core Java

Basics of Java and Core Java

Java is a general purpose programming language based on the concepts of high-level object-oriented programming language and which derives most of the syntax from C and C++. Core Java, on the other hand, is just a part of Java used for the development of portable code for both desktop applications and server environments.

What is computer Program

computer program is a collection of instructions that can be executed by a computer to perform a specific task. Most computer devices require programs to function properly.
A computer program is usually written by a computer programmer in a programming language. From the program in its human-readable form  source code

compiler or assembler can derive machine code—a form consisting of instructions that the computer can directly execute. Alternatively, a computer program may be executed with the aid of an interpreter.

Junit FrameWork

Junit Framework:Its java unit testing framework.maily used for unit testing purpose.
Latest version of Junit is:jupitor junit (junit 5)

Annotation:it provides metadata to the classes and methods.Annotation starts with symbol @ followed by name.

Junit 5 is the latest version --that name is Jupiter Junit

Annotations:
Junit 4          Jupiter Junit
@BeforeClass or @BeforeAll
@Before  or    @BeforeEach
@Test @Test
@After         @AfterEach
@AfterClass    @AfterAll
@Ignore        @Disabled
@Runwith       @Runwith
@Suite         @Suite


@BeforeClass:first this block of code will execute only once before executing any test method
only precondition steps for test method should be written inside this block
Syntax:
@BeforeClass/@BeforeAll
public static void methodName(){

//precondition code

}
@Before:this annotated method will execute before every test method

@Before/@BeforeEach
public void setUp(){
//write the code
}
@Test:only test steps should be written inside this method
we can write more than one @Test annotations in junit/testNG class.

@Test
public void testMethodName(){
//only test steps

}
@Test
public void test2(){test steps code}

Note:you can write multiple @Test annotations but method name must be different

@After:this annotated method will be executed after each test method

@After/@AfterEach
public void tearDown(){
//destroycode
}
@AfterClass:this annotated method will be executed after all the test methods of the class

@AfterClass/@AfterAll
public static void afterClass(){
//destroycode
}

@Ignore:if you want to ignore the execution of any test method, just write @Ignore above the @Test annotation

@Ignore
@Test
public void test1(){}

Execution order

@BeforeClass/@BeforeAll
.
.
.
@Before/@BeforeEach
.
.
@Test
.
.
@After/@AfterEach
.
.
@Before(if one more test method is there)/@BeforeEach
.
.
@Test(2nd test method)
.
.
@After/@AfterEach
.
.
@AfterClass/@AfterAll

Features :

  •  JUnit is an open source framework which is used for writing & running tests.
  •  Provides Annotation to identify the test methods.
  •  Provides Assertions for testing expected results.
  •  Provides Test runners for running tests.
  •  JUnit tests allow you to write code faster which increasing quality
  •  JUnit is elegantly simple. It is less complex & takes less time.
  •  JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results. 
  •  JUnit tests can be organized into test suites containing test cases and even other test suites.
  •  Junit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.
  • The @Category annotation has been replaced by the @Tag annotation.
  • JUnit 5 adds a new set of assertion methods.
  • Runners have been replaced with extensions, with a new API for extension implementors.
  • JUnit 5 introduces assumptions that stop a test from executing.
  • JUnit 5 supports nested and dynamic test classes.
====================================================================

The Assertions class and its methods

The org.junit.jupiter.api.Test annotation denotes a test method. Note that the @Test annotation now comes from the JUnit 5 Jupiter API package instead of JUnit 4's org.junit package. The testConvertToDecimalSuccess method first executes the MathTools::convertToDecimal method with a numerator of 3 and a denominator of 4, then asserts that the result is equal to 0.75. The org.junit.jupiter.api.Assertions class provides a set of static methods for comparing actual and expected results. The Assertions class has the following methods, which cover most of the primitive data types:
  • assertArrayEquals compares the contents of an actual array to an expected array.
  • assertEquals compares an actual value to an expected value.
  • assertNotEquals compares two values to validate that they are not equal.
  • assertTrue validates that the provided value is true.
  • assertFalse validates that the provided value is false.
  • assertLinesMatch compares two lists of Strings.
  • assertNull validates that the provided value is null.
  • assertNotNull validates that the provided value is not null.
  • assertSame validates that two values reference the same object.
  • assertNotSame validates that two values do not reference the same object.
  • assertThrows validates that the execution of a method throws an expected exception (you can see this in the testConvertToDecimalInvalidDenominator example above).
  • assertTimeout validates that a supplied function completes within a specified timeout.
  • assertTimeoutPreemptively validates that a supplied function completes within a specified timeout, but once the timeout is reached it kills the function's execution.
 --------------------------------------------------------------------------------------------------------------------

Running your unit test

In order to run JUnit 5 tests from a Maven project, you need to include the maven-surefire-plugin in the Maven pom.xml file and add a new dependency. Listing 3 shows the pom.xml file for this project.

Listing 3. Maven pom.xml for an example JUnit 5 project


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.javaworld.geekcap</groupId>
      <artifactId>junit5</artifactId>
      <packaging>jar</packaging>
      <version>1.0-SNAPSHOT</version>
      <build>
          <plugins>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <version>3.8.1</version>
                  <configuration>
                      <source>8</source>
                      <target>8</target>
                  </configuration>
              </plugin>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-surefire-plugin</artifactId>
                  <version>3.0.0-M4</version>
              </plugin>
          </plugins>
      </build>
      <name>junit5</name>
      <url>http://maven.apache.org</url>
      <dependencies>
          <dependency>
              <groupId>org.junit.jupiter</groupId>
              <artifactId>junit-jupiter</artifactId>
              <version>5.6.0</version>
              <scope>test</scope>
          </dependency>
      </dependencies>
  </project>

JUnit 5 dependencies

JUnit 5 packages its components in the org.junit.jupiter group and we need to add the junit-jupiter artifact, which is an aggregator artifact that imports the following dependencies:
  • junit-jupiter-api defines the API for writing tests and extensions.
  • junit-jupiter-engine is the test engine implementation that runs the unit tests.
  • junit-jupiter-params provides support for parameterized tests.
Next, we need to add the maven-surefire-plugin build plug-in in order to run the tests.
Finally, be sure to include the maven-compiler-plugin with a version of Java 8 or later, so that you'll be able to use Java 8 features like lambdas.

Run it!

Use the following command to run the test class from your IDE or from Maven:
mvn clean test
If you're successful, you should see output similar to the following:

[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.javaworld.geekcap.math.MathToolsTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.04 s - in com.javaworld.geekcap.math.MathToolsTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.832 s
[INFO] Finished at: 2020-02-16T08:21:15-05:00
[INFO] ------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------

New in JUnit 5: Tags

Before wrapping up this introduction to the core of JUnit 5, I'll show you how to use tags to selectively run different test cases in different scenarios. Tags are used to identify and filter specific tests that you want to run in different scenarios. For example, you can tag a test class or a test method as an integration test and another as development. The names and uses of the tags are all up to you.
We'll create three new test classes and tag two of them as development and one as production, presumably to differentiate between tests you want to run when building for different environments

Listing 6. Tags, Test 1 (TestOne.java)


package com.javaworld.geekcap.tags;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Tag("Development")
class TestOne {
    @Test
    void testOne() {
        System.out.println("Test 1");
    }
}

Listing 7. Tags, Test 2 (TestTwo.java)


package com.javaworld.geekcap.tags;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Tag("Development")
class TestTwo {
    @Test
    void testTwo() {
        System.out.println("Test 2");
    }
}

Listing 8. Tags, Test 3 (TestThree.java)

package com.javaworld.geekcap.tags;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Tag("Production")
class TestThree {
    @Test
    void testThree() {
        System.out.println("Test 3");
    }
}
Tags are implemented through annotations, and you can annotate either an entire test class or individual methods in a test class; furthermore, a class or a method can have multiple tags. In this example, TestOne and TestTwo are annotated with the "Development" tag, and TestThree is annotated with the "Production" tag. We can filter test runs in different ways based on tags. The simplest of these is to specify a test in your Maven command line; for example, the following only executes tests tagged as "Development":
mvn clean test -Dgroups="Development"
The groups property allows you to specify a comma-separated list of tag names for the tests that you want JUnit 5 to run. Executing this yields the following output:
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.javaworld.geekcap.tags.TestOne
Test 1
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.029 s - in com.javaworld.geekcap.tags.TestOne
[INFO] Running com.javaworld.geekcap.tags.TestTwo
Test 2
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 s - in com.javaworld.geekcap.tags.TestTwo
Likewise, we could execute just the "Production" tests as follows:
mvn clean test -Dgroups="Production"
Or both "Development" and "Production" as follows:
mvn clean test -Dgroups="Development, Production"
Test suite Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.
example:
@RunWith(Suite.class)
@Suite.SuiteClasses({ TestJunit1.class ,TestJunit2.class })


Limitations of Junit:
1)dependent testcases cannot be executed
2)you cannot prioritize the test cases
3)you dont have an option to do datadriven testing with an annotation.

TestNG Framework & Programs

TestNG is a next-generation testing framework. designed to simplify a broad range of testing needs, from unit testing (testing a class in isolation of the others) to integration testing (testing entire systems made of several classes, several packages, and even several external frameworks, such as application servers).



Advantages:

  1. TestNg provides rich annotation support
  2. TestNg generates better html/xslt reports
  3. we can prioritize the testcases(@Test methods)ex: @Test(priority=1)
  4. we can skip the testcases ex:@Test(enabled=false)
  5. we can set dependancy among the test methods ex:@Test(dependsOnMethods={"test1"})
  6. we can group the test cases ex:@Test(groups={"smoke/sanity/regression"})
  7. we can run the testcases parallally on multiple browsers
  8. we can do datadriven testing using @DataProvider annotation
  9. we can supply parameter values from xml file using @Parameters annotation

Installing TestNG in Eclipse:

Install via Eclipse Marketplace

Go to the TestNG page on the Eclipse Market Place and drag the icon called "Install" onto your workspace.

Install from update site:

  • Go to Help --> Install New Software...
  • Enter the update site URL in "Work with:" field:
  • Make sure the check box next to URL is checked and click Next.
  • Eclipse will then guide you through the process.

Writing a test is typically a three-step process:

  • Write the business logic of your test and insert TestNG annotations in your code.
  • Add the information about your test (e.g. the class name, the groups you wish to run, etc...) in a testng.xml file or in build.xml.
  • Run TestNG.

2. Annotations:

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


@BeforeSuite

public void beforeSuite(){

//write the code

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


@AfterSuite

public void afterSuite(){

//code here

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


@BeforeTest

public void beforeTest(){



//code here;
}
  • @AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.


@AfterTest

public void afterTest(){

//code here;

}
  • @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.
@BeforeGroups
public void beforeGroups(){
//code here;
}

  • @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.
@AfterGroups
public void afterGroups(){
//code here;
}
  • @BeforeClass: The annotated method will be run before the first test method in the current class is invoked.


@BeforeClass

public void beforeClass(){

//precondition code for test

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

@AfterClass

public void afterClass(){

destroycode;

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

@BeforeMethod

public void setup(){

precondition code for every testcode

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

public void tearDown(){

destroycode;

}
  • @DataProvider: Marks a method as supplying data for a test method. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
Example:
  public class DataproviderDemo{
  
  @DataProvider(name="name of the dataprovider")
  public Object[][] methodName(){
  
  Object[][] data=new Object[rows][cols];
  //rows tells you number of times test has to be executed
  //columns will tell you number of parameters in the test 
  mehod
  Object[][] data=new object[3][2];
  //first row
  data[0][0]="uname1";
  data[0][1]="pwd1";
  //2nd row
  data[1][0]="uname2";
  data[1][1]="pwd2";
  
  //3rd row
  data[2][0]="uname3";
  data[2][1]="pwd3";
  return data;
  }
  @Test(dataProvider="dataprovidername/dataprovidermethodname")
  public void loginTest(String uname,String pwd){
  
  Sop(uname+"  "+pwd);
  }
  }
    
  }
------------------------------------------------------------
@Parameters: Describes how to pass parameters to a @Test method.
To do this, we need to declare parameter tag in xml file


 using 'name' and 'value' attribute.

Where the name attribute of the tag defines name of the

 parameter and the value attribute defines the value of the 

 parameter.
parameter names are declared inside the class and above the
method
syntax:
public class ParameterDemo{
@Parameters({"parameter1","parameter2",..})
@Test
public void test(String parameter1,String parameter2){

//type the username
driver.findElement(By.name("")).sendKeys(parameter1);
//type the password
driver.findElement(By.name("")).sendKeys(parameter2);
logic inside the method
}

}
How To Create an testng.xml file for particular class
1)right click on the class
2)select TESTNG option-->convert to testNG
3)give the suite name,test name and xml file location
4)click on finish button

//parameter values will be supplied from testng.xml file
testng.xml format
----------------------------------------------------------------------------
<suite name="suitename" parallel="none">
<test name="testname">
<parameter name="parameter1" value="valueofparameter1"/>
<parameter name="parameter2" value="value of parameter2"/>
<classes>
 <class name="packagename.classname1"/>
 <class name="packagename.classname2"/>
 </classes>
 </test>
  </suite>
 ============================================
  • @Test: Marks a class or a method as part of the test.


@Test
public void methodTest(){
//only test steps;
}

@Test Keywords/Parameters:

dataProviderThe name of the data provider for this test method.
this keyword is used to map between @DataProvider and @Test
Syntax:
@Test(dataProvider="dataprovidername/dataprovidermethodname")



dependsOnGroups: The list of groups this method depends on.

Syntax:

@Test(dependsOnGroups={"groupname"})

public void dgroup(){}


dependsOnMethods: The list of methods this method depends on.

Syntax:

@Test(dependsOnMethods={"methodname1","method2"})

public void dmethod(){}


alwaysRun: If set to true, this test method will always be run even 

if it depends on a method that failed.
@Test(alwaysRun=true,dependsOnMethods={"t"})

public void t1(){}


description: The description for this method.

Syntax:
@Test(description="write small description")

enabled: Whether methods on this class/method are enabled.

Syntax:
@Test(enabled=false)--this test method will skip


expectedExceptions: The list of exceptions that a test method is expected to throw. If no exception or a different than one on this list is thrown, this test will be marked a failure.
Syntax:

@Test(expectedExceptions={"e1","e2"..})

groups: The list of groups this class/method belongs to.

Grouping in Automation is a quite an interesting feature through which you can easily categorize your test cases based on requirements.


For Example- If we have 200 test cases out of these some are end-to-end test cases, some are functional test cases and some are regression or smoke test cases so if you don’t categorize these test cases these all test cases will come under one common category.

Group Selenium Script using TestNG

For grouping in Selenium, we have to use the TestNG feature through which we can create groups and maintain them easily.

    Syntax

@Test(groups={"groupname"})

public void methodname(){}

Example:

 @Test(groups={"Smoke"},priority=1,description="")
public void m1(){}


We can create multiple groups as well

Syntax
 @Test(groups={"group1","group2"})
public void methodname(){}

We can include and exclude groups through testng.xml file

After grouping in Selenium we can specify the include and exclude in testng.xml.

<include> – It tells testng.xml that which group we need to execute.


<exclude>- It tells testng.xml which group we have to Skip

------------------------------------------------------
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="SuiteGroups" parallel="none">
  <test name="Testgroups">
    <groups>
       <run>
          <include name="Smoke" />
          <exclude name="Regression"/>
       </run>
     </groups>
    <classes>
      <class name="testngDemo.TestGroupDemo"/>
<class name="testngDemo.TestGroupDemo122"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

I created a new tag called group, an inside group we have mentioned includes and excludes tags, and 

we have mentioned the group name, which we have to include and exclude.


Once you run the above xml it will run all the test cases, which belong to the Smoke group category.

invocationCount: The number of times this method should be invoked.

Syntax:

@Test(invocationCount=3)

successpercentage: The percentage of success expected from this method

Timeout: The maximum number of milliseconds this test should take.

@Test(timeOut=3000)

threadPoolSize: The size of the thread pool for this method. The method will be invoked from multiple threads as specified by invocationCount.

priority: The priority for this test method. Lower priorities will be scheduled first.
@Test(priority=1)
public void t1(){}
@Test(priority=2)
public void l1(){}

How to Specify the particular class methods using include & exclude tags?


You can also specify groups and methods to be included and excluded:
<suite name="nameofthesuite">
<test name="Regression1">
  <groups>
    <run>
      <exclude name="brokenTests"  />
      <include name="checkinTests"  />
    </run>
  </groups>
  
  <classes>
    <class name="test.IndividualMethodsTest">
      <methods>
        <include name="testMethod" />
<exclude name="test2"/>
      </methods>
    </class>
<class name="test.IndependentTest"/>
  </classes>
</test>
</suite>

TestNg Reports:

Importance of Reporting in Selenium?
Ans-1- Reports helps you to identify the status of the test case (Pass/Fail/Skip).

2- Using reports we calculate the time taken by each test case that helps to calculate ROI(Return of Investment).

3- You can share automation reports with your team and clients as well to share the status of testing progress etc.

TestNG will provide three types of reports?
1)First open Default test.html
2)Second open emailable-report.html
3)Third open Index.html

if you expand test-output folder under the same project you can find the above three reports.
--------------------------------------------------------------------------------------
ReportNg Reports:
we need two dependencies
1) ReportNG --[org.uncommons » reportng]
2)Google Guice Core Library
include below listeners tag in testNg.xml  after suite tag
<listeners>
      <listener class-name="org.uncommons.reportng.HTMLReporter"/>
      <listener class-name="org.uncommons.reportng.JUnitXMLReporter"/>
  </listeners>
==================================================================
How to generate a report in link format:
Reporter.log("<a href=\"D:\\screenshot\\error.jpg\">screenshot</a>");

wherever you are adding the above line of anchor tag just add the below line of code inside the method in first
System.getProperty("org.uncommons.reportng.escape-output","false");

if you want to open the screenshot in another/separate tab then change the 1544 line like below
Reporter.log("<a target=\"blank\" href=\"D:\\screenshot\\error.jpg\">screenshot</a>");
if you want to add a small thumbnail in the reports.
Reporter.log("<a target=\"blank\" href=\"D:\\screenshot\\error.jpg\">screenshot</a>");
Reporter.log("<br>");
Reporter.log("<a target=\"blank\" href=\"D:\\screenshot\\error.jpg\"><img src=\"D:\\screenshot\\error.jpg\" height=200 width=200></img></a>");
======================================================================

How to Run Parallel tests, classes, and methods

=======================================================================
The parallel attribute on the <suite> tag can take one of the following values:
<suite name="My suite" parallel="methods" thread-count="5">
view source print?
<suite name="My suite" parallel="tests" thread-count="5">
<suite name="My suite" parallel="classes" thread-count="5">
<suite name="My suite" parallel="instances" thread-count="5">

parallel="methods": TestNG will run all your test methods in separate threads. Dependent methods will also run in separate threads but they will respect the order that you specified.

parallel="tests": TestNG will run all the methods in the same <test> tag in the same thread, but each <test> tag will be in a separate thread. This allows you to group all your classes that are not thread-safe in the same <test> and guarantee they will all run in the same thread while taking advantage of TestNG using as many threads as possible to run your tests.

parallel="classes": TestNG will run all the methods in the same class in the same thread, but each class will be run in a separate thread.

parallel="instances": TestNG will run all the methods in the same instance in the same thread, but two methods on two different instances will be running in different threads.