0% found this document useful (0 votes)
42 views6 pages

TestNG C# Automation Framework

This document contains code for automating tests of a web application using Selenium and C#. It defines classes for the base test page, a login page object model, and a test execution class. The base class contains common methods like initializing the Chrome driver, taking screenshots, logging actions. The login page class defines page elements and a login method. The test execution class inherits from the base and contains test initialization, cleanup and sample tests using the page object model.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views6 pages

TestNG C# Automation Framework

This document contains code for automating tests of a web application using Selenium and C#. It defines classes for the base test page, a login page object model, and a test execution class. The base class contains common methods like initializing the Chrome driver, taking screenshots, logging actions. The login page class defines page elements and a login method. The test execution class inherits from the base and contains test initialization, cleanup and sample tests using the page object model.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DAy 2 - Lab Assignment

using [Link];
using System;
using [Link];
using [Link];
using [Link];
using [Link];

namespace POM
{
public partial class LoginPage : BasePage
{
#region Properties
public string username { get; set; }
public string password { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string mobileNumber { get; set; }
#endregion

public void Login()


{
if (username != null)
{
EnterText(txtUsername, username);

}
if(password != null)
{
EnterText(txtPassword, password);
}
Click(btnLogin);
}
}
}

using [Link];
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using System;
using [Link];
using [Link];
using [Link].X509Certificates;
using [Link];
using [Link];

namespace Frame_POMA
{

[TestClass]
public class Execution : BasePage
{
private TestContext instance;

public TestContext TestContext


{
set { instance = value; }
get { return instance; }
}

[AssemblyInitialize]
public static void AssemblyInitialize(TestContext testContext)
{
LogReport("Test Report");
[Link]("AssemblyInitialize");
}

[AssemblyCleanup]
public static void AssemblyCleanup()
{
ExtentFlush();
[Link]("AssemblyCleanup");
}

[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
[Link]("ClassInitialize");
}

[ClassCleanup]
public static void ClassCleanup()
{
[Link]("ClassCleanup");
}

[TestInitialize]
public void TestInitialize()
{
exParentTest = [Link]([Link]);
NodeCreation([Link]);
InitializeChrome();
OpenUrl("[Link]
}

[TestCleanup]
public void TestCleanup()
{
QuitChrome();
}
}
}

Base CLASS
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using static [Link];

namespace Frame_POMA
{
public class BasePage
{
public static IWebDriver driver;
public static ExtentReports extentReports;
public static ExtentTest exParentTest;
public static ExtentTest exChildTest;
public static string dirpath = "C:\\ExtentReports\\" +
[Link]("yyyyMMdd_HHmmss") + "\\";

//classlevelLog4net
private static readonly [Link] log =
[Link]([Link]().DeclaringType);

public static void LogReport(string testcase)


{
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(dirpath);
[Link]("Application is working ");
#region ABC
[Link] = "Automation Testing Report";
[Link] = [Link];

extentReports = new ExtentReports();


[Link](htmlReporter);

[Link]("AUT", "Hotel Adactin");


[Link]("Environment", "QA");
[Link]("Machine", [Link]);
[Link]("OS", [Link]);
#endregion
}
public void Log(string exp, string a)
{
switch (exp)
{
case "info":
[Link](a);
break;
case "error":
[Link](a);
break;
case "debug":
[Link](a);
break;
case "warn":
[Link](a);
break;
}
}
public void NodeCreation(string methodname)
{
exChildTest = [Link](methodname);
}
public static void TakeScreenshot(Status status, string stepDetail)
{
string path = dirpath + "TestExcelLog_" + [Link]("yyyyMMddHHmmss");
Screenshot image = ((ITakesScreenshot)driver).GetScreenshot();
[Link](path + ".png", [Link]);
[Link](status, stepDetail,
[Link](path + ".png").Build());
[Link]("Application is working ");
}
public static void ExtentFlush()
{
[Link]();
}
public void InitializeChrome()
{
driver = new ChromeDriver();
[Link]().[Link]();
[Link]().Timeouts().ImplicitWait = [Link](60);
[Link]("Application is working ");
}
public void EnterText(By by, string value)
{
try
{
[Link](by).SendKeys(value);
TakeScreenshot([Link], "Text Written on " + by + " this locator and value : " + value);
}
catch (Exception ex)
{
TakeScreenshot([Link], "Enter Text Failed : " + [Link]());
}

}
public void Clear(By by)
{
[Link](by).Clear();
}
public void Click(By by)
{
try
{
[Link](by).Click();
TakeScreenshot([Link], "Click on " + by);
Log("info", "Application is working ");

}
catch (Exception ex)
{
TakeScreenshot([Link], "Click Failed : " + [Link]());
}
}
public void OpenUrl(string url)
{
try
{
[Link] = url;
TakeScreenshot([Link], "URL Open");
}
catch (Exception ex)
{
TakeScreenshot([Link], "This Site can't be reached");
}
}
public string GetElementText(By by)
{
string text;
try
{
text = [Link](by).Text;
}
catch
{
try
{
text = [Link](by).GetAttribute("value");
}
catch
{
text = [Link](by).GetAttribute("innerHTML");
}
}
return text;
}
public string GetElementState(By by)
{
string elementState = [Link](by).GetAttribute("Disabled");

if (elementState == null)
{
elementState = "enabled";
}
else if (elementState == "false")
{
elementState = "enabled";
}
else if (elementState == "true")
{
elementState = "disabled";
}
return elementState;
}
public static string ExecuteJavaScriptCode(string javascriptCode)
{
string value = null;
try
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
value = (string)[Link](javascriptCode);
}
catch (Exception)
{

}
return value;
}
public static void ThreadSleepWait(int seconds)
{
//Mili Seconds =

[Link](seconds * 1000);
}
public void QuitChrome()
{
[Link]();
}

}
}

Common questions

Powered by AI

The 'InitializeChrome' method sets up the Google Chrome browser environment by creating a new ChromeDriver instance, maximizing the window, and setting an implicit wait of 60 seconds. This preparation ensures that each test starts with a fresh browser session, providing a consistent testing environment and reducing setup redundancy in individual test cases .

Using implicit waits instructs the WebDriver to poll the DOM for a specified time (60 seconds in this case) until elements are present, simplifying synchronization across tests without explicit wait commands. This reduces code complexity and ensures elements have fully loaded before interaction, improving test stability compared to relying solely on explicit waits or Thread.sleep .

The 'GetElementState' method checks whether a web element is enabled or disabled by evaluating its 'Disabled' attribute. This validation helps in conditionally executing tests based on UI states, ensuring actions are performed only when elements are interactable, thereby preventing test failure due to unresponsive UI components and strengthening test script reliability .

'ThreadSleepWait' pauses the test execution for a specified duration, ensuring element availability or load completion. While this can alleviate timing issues, it risks introducing inefficiency and reduced test reliability if page dynamics change, as it uses fixed delays without consideration for actual page load conditions. Over-reliance on it can lead to longer test runs and mask timing problems .

The 'AssemblyInitialize' and 'AssemblyCleanup' methods define the setup and teardown routines that execute once per test assembly. 'AssemblyInitialize' is used to set up resources shared across tests (e.g., initializing test reports), while 'AssemblyCleanup' is responsible for finalizing processes like flushing reports. These methods ensure each test suite runs in a clean and consistent environment and can impact testing reliability and resource management significantly .

The 'NodeCreation' method serves to create hierarchical nodes within the ExtentReport, allowing individual test steps to be documented and tracked under a parent test case node. This helps organize test reports into a clear structure, facilitating easier navigation and analysis of test steps relative to their test case context .

The 'TakeScreenshot' method captures the current state of the application window during test execution, saving the screenshot with a timestampped filepath. It is used in conjunction with logging to record both successful and failed test steps, providing visual documentation of test outcomes. This aids developers in diagnosing the exact UI state when errors occur, thereby facilitating quicker debugging .

The POM structure enhances maintainability by encapsulating web element interactions within page-specific classes, making tests more organized, readable, and easier to update. Changes to the UI only necessitate updates in the corresponding page class rather than every test, reducing duplication and improving scalability .

The 'Login' method in the LoginPage class is responsible for automating the login process by handling user inputs such as username and password. It checks whether the username and password properties are not null, then enters these values into the designated fields using the 'EnterText' method. The method concludes by simulating a button click on the login button using the 'Click' method. This flow ensures only filled fields are populated, reducing the likelihood of errors during automated login testing .

'ExtentReports' enhances reporting by providing detailed and visually structured HTML reports that include system information, environment details, and step-by-step test documentation. It integrates screenshots and logs of test actions and results, making it easier to analyze test performance and identify issues .

You might also like