A comprehensive, scalable, and maintainable test automation framework built with Selenium WebDriver and C# .NET 10. Designed for enterprise-grade web application testing with support for CI/CD integration, detailed reporting, and future MCP (Model Context Protocol) extensibility.
Get up and running in 5 minutes:
# 1. Clone the repository
git clone https://github.com/amitbad/CSharp-Selenium-Test-Automation.git
cd Test-Automation-CS-Selenium
# 2. Restore dependencies
dotnet restore
# 3. Build the solution
dotnet build
# 4. Update the base URL in appsettings.json
# Edit: tests/TestAutomation.Tests/appsettings.json
# Change "BaseUrl" to your application URL
# 5. Run tests
dotnet test
# 6. Run specific test categories
dotnet test --filter "Category=API" # API tests only
dotnet test --filter "Category=UI" # UI tests only
dotnet test --filter "Category=Smoke" # Smoke tests
# 7. Run headless (for CI/CD)
TEST_AUTO_HEADLESS=true dotnet test
# 8. View the report
open tests/TestAutomation.Tests/Reports/TestReport_*.htmlThat's it! For detailed documentation, continue reading below.
- Features
- Architecture
- Cross-Platform Support
- Prerequisites
- Installation
- Project Structure
- Configuration
- NUnit Testing Framework
- Writing Tests
- Page Object Model
- Locator Management
- Running Tests
- Reporting
- API Testing
- CI/CD Integration
- Selenium Grid
- MCP Integration
- Best Practices
- Troubleshooting
- Contributing
- Selenium WebDriver 4.25 - Latest Selenium with modern browser support
- REST API Testing - Built-in API client with RestSharp for hybrid testing
- NUnit 4.2 - Industry-standard .NET testing framework with rich attributes
- FluentAssertions - Readable, expressive assertion syntax
- Page Object Model (POM) - Clean separation of test logic and page interactions
- JSON-based Locators - Externalized, maintainable element locators
- Multi-browser Support - Chrome, Firefox, Edge, Safari
- Parallel Test Execution - Thread-safe driver management
- Automatic Driver Management - WebDriverManager handles driver binaries
- Data-Driven Testing - TestCase, TestCaseSource for parameterized tests
- Hybrid Testing - Combine API and UI tests for faster, more reliable E2E tests
- Environment-based Configuration - Separate configs for Dev, Staging, Production
- Environment Variable Override - CI/CD friendly configuration
- Secure Secrets Management - No hardcoded credentials
- Extent Reports - Beautiful HTML reports with screenshots
- Serilog Logging - Structured logging to console and file
- Screenshot on Failure - Automatic screenshot capture
- GitHub Actions - Pre-configured workflows
- Jenkins Pipeline - Jenkinsfile included
- Docker Support - Ready for containerized execution
- MCP Integration Foundation - Prepared for AI-assisted testing
- Extensible Architecture - Easy to add new capabilities
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Test Layer β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β SampleTests β β LoginTests β β OtherTests β β
β ββββββββ¬βββββββ ββββββββ¬βββββββ ββββββββ¬βββββββ β
β β β β β
β ββββββββββββββββββΌβββββββββββββββββ β
β βΌ β
β βββββββββββββββ β
β β BaseTest β β
β ββββββββ¬βββββββ β
ββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββ
β Page Layer β
β ββββββββββββββββββΌβββββββββββββββββ β
β βΌ βΌ βΌ β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β LoginPage β β HomePage β β OtherPages β β
β ββββββββ¬βββββββ ββββββββ¬βββββββ ββββββββ¬βββββββ β
β β β β β
β ββββββββββββββββββΌβββββββββββββββββ β
β βΌ β
β βββββββββββββββ β
β β BasePage β β
β ββββββββ¬βββββββ β
ββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββ
β Framework Layer β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β β Driver β β Locators β β Reporting β β β
β β β Manager β β Repository β β Manager β β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β β Config β β Logger β β Utilities β β β
β β β Manager β β β β β β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
This framework is fully cross-platform and works on Windows, macOS, and Linux.
| Component | Windows | macOS | Linux |
|---|---|---|---|
| .NET 10 SDK | β | β | β |
| Selenium WebDriver | β | β | β |
| Chrome | β | β | β |
| Firefox | β | β | β |
| Edge | β | β | β |
| Safari | β | β | β |
| GitHub Actions | β | β | β |
| Jenkins | β | β | β |
- .NET 10 is cross-platform (runs natively on all OS)
- WebDriverManager automatically downloads correct browser drivers per OS
- Path handling uses
Path.Combine()for OS-agnostic paths - No platform-specific code in the framework
# Using winget
winget install Microsoft.DotNet.SDK.10
# Or download installer from https://dotnet.microsoft.com/download# Using Homebrew
brew install dotnet@10
# Or download installer from https://dotnet.microsoft.com/download# Add Microsoft package repository
wget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
# Install .NET 10 SDK
sudo apt-get update
sudo apt-get install -y dotnet-sdk-10.0
# For headless Chrome testing, install dependencies
sudo apt-get install -y chromium-browser- Google Chrome (recommended)
- Mozilla Firefox
- Microsoft Edge
- Safari (macOS only)
# Check .NET version (works on all platforms)
dotnet --version
# Expected: 10.0.x
# Check Git
git --versiongit clone https://github.com/yourusername/Test-Automation-CS-Selenium.git
cd Test-Automation-CS-Seleniumdotnet restoredotnet build# Copy example environment file
cp .env.example .env
# Edit .env with your settings
# Update appsettings.json with your application URLdotnet testTest-Automation-CS-Selenium/
βββ .github/
β βββ workflows/
β βββ test.yml # Main CI workflow
β βββ scheduled-tests.yml # Scheduled regression tests
βββ src/
β βββ TestAutomation.Framework/
β βββ Api/ # API Testing
β β βββ ApiClient.cs # REST client wrapper
β β βββ ApiResponse.cs # Response models
β β βββ ApiAssertions.cs # Fluent assertions
β β βββ Models/ # Request/Response models
β β βββ AuthModels.cs
β β βββ CommonModels.cs
β βββ Configuration/
β β βββ ConfigurationManager.cs
β β βββ TestSettings.cs
β βββ Driver/
β β βββ BrowserType.cs
β β βββ DriverFactory.cs
β β βββ DriverManager.cs
β βββ Locators/
β β βββ ElementLocator.cs
β β βββ LocatorRepository.cs
β β βββ LocatorType.cs
β β βββ PageLocators.cs
β βββ Logging/
β β βββ Logger.cs
β βββ MCP/
β β βββ IMcpClient.cs
β β βββ McpTestContext.cs
β β βββ McpIntegrationReadme.md
β βββ Pages/
β β βββ BasePage.cs
β βββ Reporting/
β β βββ ExtentReportManager.cs
β βββ Utilities/
β β βββ RetryHelper.cs
β β βββ TestDataHelper.cs
β β βββ WaitHelper.cs
β βββ TestAutomation.Framework.csproj
βββ tests/
β βββ TestAutomation.Tests/
β βββ Base/
β β βββ BaseTest.cs
β βββ Locators/
β β βββ LoginPage.json
β β βββ HomePage.json
β βββ Pages/
β β βββ LoginPage.cs
β β βββ HomePage.cs
β βββ TestData/
β β βββ users.json
β βββ Tests/
β β βββ API/ # API tests
β β β βββ SampleApiTests.cs
β β β βββ AuthApiTests.cs
β β βββ UI/ # UI tests
β β β βββ SampleTests.cs
β β β βββ LoginTests.cs
β β βββ Hybrid/ # Combined API + UI tests
β β βββ HybridTestExample.cs
β βββ appsettings.json
β βββ appsettings.Development.json
β βββ appsettings.Staging.json
β βββ appsettings.Production.json
β βββ TestAutomation.Tests.csproj
βββ .env.example
βββ .gitignore
βββ docker-compose.yml # Selenium Grid setup
βββ TestAutomation.sln
βββ Jenkinsfile
βββ README.md
| File | Purpose |
|---|---|
appsettings.json |
Default configuration |
appsettings.Development.json |
Development environment overrides |
appsettings.Staging.json |
Staging environment overrides |
appsettings.Production.json |
Production environment overrides |
{
"TestSettings": {
"BaseUrl": "https://your-app.com",
"Browser": "Chrome",
"Headless": false,
"ImplicitWaitSeconds": 10,
"ExplicitWaitSeconds": 30,
"PageLoadTimeoutSeconds": 60,
"MaximizeWindow": true,
"ScreenshotOnFailure": true,
"ScreenshotPath": "Screenshots",
"ReportPath": "Reports",
"Environment": "Development",
"EnableDetailedLogging": true,
"RetryCount": 0,
"UseRemoteDriver": false,
"RemoteWebDriverUrl": null
}
}Environment variables override configuration files. Prefix with TEST_AUTO_:
| Variable | Description | Example |
|---|---|---|
TEST_ENVIRONMENT |
Environment name | Staging |
TEST_AUTO_BASE_URL |
Application URL | https://staging.app.com |
TEST_AUTO_BROWSER |
Browser to use | Chrome, Firefox, Edge |
TEST_AUTO_HEADLESS |
Headless mode | true, false |
TEST_AUTO_USE_REMOTE_DRIVER |
Use Selenium Grid | true, false |
TEST_AUTO_REMOTE_WEBDRIVER_URL |
Grid URL | http://localhost:4444/wd/hub |
# Linux/macOS
export TEST_ENVIRONMENT=Staging
export TEST_AUTO_BASE_URL=https://staging.example.com
export TEST_AUTO_HEADLESS=true
# Windows PowerShell
$env:TEST_ENVIRONMENT = "Staging"
$env:TEST_AUTO_BASE_URL = "https://staging.example.com"
$env:TEST_AUTO_HEADLESS = "true"
# Windows CMD
set TEST_ENVIRONMENT=Staging
set TEST_AUTO_BASE_URL=https://staging.example.com
set TEST_AUTO_HEADLESS=trueThis framework uses NUnit 4.2 as the testing framework along with FluentAssertions for readable assertions.
| Package | Version | Purpose |
|---|---|---|
NUnit |
4.2.2 | Core testing framework |
NUnit3TestAdapter |
4.6.0 | Test discovery and execution |
NUnit.Analyzers |
4.4.0 | Code analysis for best practices |
Microsoft.NET.Test.Sdk |
17.12.0 | .NET test SDK |
FluentAssertions |
6.12.1 | Fluent assertion syntax |
coverlet.collector |
6.0.2 | Code coverage collection |
| Attribute | Description | Example |
|---|---|---|
[TestFixture] |
Marks a class as containing tests | [TestFixture] |
[TestFixtureSetUp] |
One-time setup for the fixture | [OneTimeSetUp] |
[TestFixtureTearDown] |
One-time teardown for the fixture | [OneTimeTearDown] |
[SetUp] |
Runs before each test | [SetUp] |
[TearDown] |
Runs after each test | [TearDown] |
[Parallelizable] |
Enable parallel execution | [Parallelizable(ParallelScope.Self)] |
| Attribute | Description | Example |
|---|---|---|
[Test] |
Marks a method as a test | [Test] |
[TestCase] |
Data-driven test with inline data | [TestCase("user", "pass")] |
[TestCaseSource] |
Data-driven test with external source | [TestCaseSource(nameof(TestData))] |
[Category] |
Categorize tests for filtering | [Category("Smoke")] |
[Description] |
Add test description | [Description("Verify login")] |
[Ignore] |
Skip a test | [Ignore("Bug #123")] |
[Retry] |
Retry failed tests | [Retry(3)] |
[Timeout] |
Set test timeout | [Timeout(30000)] |
[Order] |
Control test execution order | [Order(1)] |
// NUnit Classic Assertions
Assert.That(actual, Is.EqualTo(expected));
Assert.That(list, Has.Count.EqualTo(5));
Assert.That(value, Is.GreaterThan(10));
Assert.IsTrue(condition);
Assert.IsNotNull(obj);
// FluentAssertions (Recommended - more readable)
actual.Should().Be(expected);
list.Should().HaveCount(5);
value.Should().BeGreaterThan(10);
condition.Should().BeTrue();
obj.Should().NotBeNull();
// String assertions
text.Should().Contain("expected");
text.Should().StartWith("Hello");
text.Should().MatchRegex(@"\d+");
// Collection assertions
list.Should().Contain(item);
list.Should().BeInAscendingOrder();
list.Should().OnlyContain(x => x > 0);
// Exception assertions
action.Should().Throw<InvalidOperationException>()
.WithMessage("*error*");βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Test Execution Flow β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β [OneTimeSetUp] ββββββΊ Initialize Logger β
β β Log test suite start β
β βΌ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β For Each Test: β β
β β β β
β β [SetUp] βββββββΊ Create Extent Report test β β
β β β Initialize WebDriver β β
β β β Log test start β β
β β βΌ β β
β β [Test] ββββββββΊ Execute test steps β β
β β β Use Page Objects β β
β β β Perform assertions β β
β β βΌ β β
β β [TearDown] ββββΊ Log test result β β
β β Take screenshot (on failure) β β
β β Quit WebDriver β β
β β Update Extent Report β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βΌ β
β [OneTimeTearDown] ββΊ Flush Extent Report β
β Close Logger β
β Generate HTML report β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Enable parallel execution at different levels:
// Parallel at assembly level (in AssemblyInfo.cs or test file)
[assembly: Parallelizable(ParallelScope.Fixtures)]
[assembly: LevelOfParallelism(4)]
// Parallel at fixture level
[TestFixture]
[Parallelizable(ParallelScope.Self)]
public class MyTests : BaseTest { }
// Parallel at test level
[Test]
[Parallelizable(ParallelScope.Self)]
public void MyTest() { }ParallelScope Options:
None- No parallel executionSelf- Test/fixture can run in parallel with othersChildren- Child tests can run in parallelFixtures- Fixtures can run in parallelAll- Maximum parallelism
// Inline TestCase
[Test]
[TestCase("admin", "admin123", true)]
[TestCase("user", "wrongpass", false)]
public void LoginTest(string user, string pass, bool expected) { }
// TestCaseSource with method
[Test]
[TestCaseSource(nameof(GetLoginTestData))]
public void LoginTest(string user, string pass, bool expected) { }
private static IEnumerable<TestCaseData> GetLoginTestData()
{
yield return new TestCaseData("admin", "admin123", true)
.SetName("Admin Login")
.SetCategory("Smoke");
yield return new TestCaseData("user", "wrong", false)
.SetName("Invalid Login")
.SetCategory("Negative");
}
// TestCaseSource with external class
[Test]
[TestCaseSource(typeof(LoginTestData), nameof(LoginTestData.ValidLogins))]
public void ValidLoginTest(string user, string pass) { }using NUnit.Framework;
using FluentAssertions;
using TestAutomation.Tests.Base;
using TestAutomation.Framework.Driver;
namespace TestAutomation.Tests.Tests;
[TestFixture]
[Category("Smoke")]
public class MyTests : BaseTest
{
[Test]
[Description("Verify home page loads successfully")]
public void VerifyHomePageLoads()
{
// Arrange
LogStep("Navigate to home page");
NavigateToBaseUrl();
// Act
var title = DriverManager.GetPageTitle();
// Assert
title.Should().NotBeNullOrEmpty();
LogInfo($"Page title: {title}");
}
}[Test]
[TestCase("user1@test.com", "password1", true)]
[TestCase("invalid@test.com", "wrong", false)]
public void LoginTest(string username, string password, bool shouldSucceed)
{
var loginPage = new LoginPage();
loginPage.NavigateToLoginPage();
if (shouldSucceed)
{
var homePage = loginPage.Login(username, password);
homePage.IsUserLoggedIn().Should().BeTrue();
}
else
{
loginPage.EnterUsername(username);
loginPage.EnterPassword(password);
loginPage.ClickLoginButton();
loginPage.IsErrorMessageDisplayed().Should().BeTrue();
}
}Use categories to organize and filter tests:
[Test]
[Category("Smoke")] // Quick sanity tests
[Category("Regression")] // Full regression suite
[Category("Login")] // Feature-specific
public void MyTest() { }using OpenQA.Selenium;
using TestAutomation.Framework.Pages;
using TestAutomation.Framework.Logging;
namespace TestAutomation.Tests.Pages;
public class ProductPage : BasePage
{
// Required: Page name for locator lookup
protected override string PageName => "ProductPage";
// Fallback locators (if JSON not available)
private static class Locators
{
public static By ProductTitle => By.CssSelector(".product-title");
public static By AddToCartButton => By.Id("add-to-cart");
public static By PriceLabel => By.CssSelector(".price");
}
// Page methods using fluent pattern
public ProductPage NavigateToProduct(string productId)
{
Logger.Step($"Navigating to product: {productId}");
Driver.Navigate().GoToUrl($"{Settings.BaseUrl}/products/{productId}");
WaitForPageLoad();
return this;
}
public string GetProductTitle()
{
var locator = base.Locators != null
? GetLocator("ProductTitle")
: Locators.ProductTitle;
return GetText(locator);
}
public CartPage AddToCart()
{
Logger.Step("Adding product to cart");
var locator = base.Locators != null
? GetLocator("AddToCartButton")
: Locators.AddToCartButton;
Click(locator);
return new CartPage();
}
public decimal GetPrice()
{
var locator = base.Locators != null
? GetLocator("PriceLabel")
: Locators.PriceLabel;
var priceText = GetText(locator);
return decimal.Parse(priceText.Replace("$", ""));
}
}| Method | Description |
|---|---|
FindElement(By) |
Find element with wait |
FindElements(By) |
Find multiple elements |
Click(By) |
Click element |
Type(By, string) |
Type text into element |
GetText(By) |
Get element text |
IsElementDisplayed(By) |
Check if element visible |
WaitForElementVisible(By) |
Wait for element to be visible |
WaitForElementClickable(By) |
Wait for element to be clickable |
SelectByText(By, string) |
Select dropdown option |
Hover(By) |
Hover over element |
ScrollIntoView(By) |
Scroll element into view |
The framework uses a simplified one-line format for easy maintenance:
{
"PageName": "LoginPage",
"Description": "Login page locators",
"Elements": {
"UsernameInput": "Id:username",
"PasswordInput": "Id:password",
"LoginButton": "CssSelector:button[type='submit']",
"ErrorMessage": "CssSelector:.error-message",
"ForgotPasswordLink": "LinkText:Forgot Password?",
"RememberMeCheckbox": "Id:remember-me"
}
}Format: "ElementName": "Type:Value"
| Type | Format Example |
|---|---|
Id |
"Id:username" |
Name |
"Name:email" |
ClassName |
"ClassName:btn-primary" |
CssSelector |
"CssSelector:button.submit" |
XPath |
"XPath://button[@type='submit']" |
LinkText |
"LinkText:Sign In" |
PartialLinkText |
"PartialLinkText:Sign" |
TagName |
"TagName:button" |
Use format placeholders {0}, {1}, etc. for dynamic values:
{
"PageName": "ProductPage",
"Elements": {
"ProductById": "XPath://div[@data-product-id='{0}']",
"CategoryItem": "CssSelector:[data-category='{0}'] .item:nth-child({1})"
}
}// Usage in Page Object
var locator = GetLocator("ProductById", productId);
Click(locator);
// Multiple parameters
var locator = GetLocator("CategoryItem", "electronics", 3);- Prefer stable attributes:
id,data-testid,name - Avoid brittle locators: Position-based XPath, generated classes
- Use CSS over XPath: Generally faster and more readable
- Keep locators short: Avoid long chains
- Use simplified format: One line per element for easy editing
dotnet testTEST_AUTO_BROWSER=Firefox dotnet testTEST_AUTO_HEADLESS=true dotnet testdotnet test --filter "Category=Smoke"
dotnet test --filter "Category=Regression"dotnet test --filter "FullyQualifiedName~LoginTests"
dotnet test --filter "Name=VerifyHomePageLoads"dotnet test --verbosity normal
dotnet test --verbosity detailedTEST_ENVIRONMENT=Staging dotnet testTests marked with [Parallelizable] run in parallel:
dotnet test -- NUnit.NumberOfTestWorkers=4HTML reports are generated automatically in the Reports folder.
Report Features:
- Test execution summary
- Pass/Fail/Skip statistics
- Screenshots on failure
- Step-by-step execution logs
- System information
- Timeline view
After test execution, report will be created at location : Reports :
Logs are stored in the Logs folder with timestamps.
The framework includes a powerful REST API testing capability built on RestSharp, enabling hybrid UI + API testing.
- Full HTTP Support - GET, POST, PUT, PATCH, DELETE
- Authentication - Bearer Token, Basic Auth, API Key
- Typed Responses - Automatic JSON deserialization
- Fluent Assertions - Chain assertions on responses
- Async/Sync - Both async and synchronous methods
- File Upload - Multipart form data support
- Request Logging - Automatic logging of requests/responses
using TestAutomation.Framework.Api;
// Create API client
var apiClient = new ApiClient("https://api.example.com");
// GET request with typed response
var response = apiClient.Get<List<User>>("/users");
response.ShouldBeSuccessful();
response.Data.Should().NotBeEmpty();
// POST request
var newUser = new { name = "John", email = "john@example.com" };
var createResponse = apiClient.Post<User>("/users", newUser);
createResponse.ShouldBeCreated();
// With authentication
apiClient.WithBearerToken("your-token");
var protectedResponse = apiClient.Get<Profile>("/profile");// Bearer Token
var client = new ApiClient("https://api.example.com")
.WithBearerToken("eyJhbGciOiJIUzI1NiIs...");
// Basic Auth
var client = new ApiClient("https://api.example.com")
.WithBasicAuth("username", "password");
// API Key
var client = new ApiClient("https://api.example.com")
.WithApiKey("your-api-key", "X-API-Key");
// Custom Headers
var client = new ApiClient("https://api.example.com")
.WithHeader("X-Custom-Header", "value");// Status code assertions
response.ShouldBeOk(); // 200
response.ShouldBeCreated(); // 201
response.ShouldBeNoContent(); // 204
response.ShouldBeBadRequest(); // 400
response.ShouldBeUnauthorized(); // 401
response.ShouldBeForbidden(); // 403
response.ShouldBeNotFound(); // 404
// Custom status code
response.ShouldHaveStatusCode(HttpStatusCode.Accepted);
// Content assertions
response.ShouldBeSuccessful();
response.ShouldHaveData();
response.ShouldContain("expected text");
// Header assertions
response.ShouldHaveHeader("Content-Type");
response.ShouldHaveHeader("X-Request-Id", "12345");
// Performance assertions
response.ShouldCompleteWithin(5000); // 5 seconds maxCombine API and UI testing for faster, more reliable tests:
[Test]
public void CreateDataViaApi_VerifyInUI()
{
// STEP 1: Create test data via API (fast)
var apiClient = new ApiClient("https://api.example.com");
var response = apiClient.Post<Order>("/orders", new {
product = "Widget",
quantity = 5
});
response.ShouldBeCreated();
var orderId = response.Data!.Id;
// STEP 2: Verify in UI
NavigateToBaseUrl();
var orderPage = new OrderPage();
orderPage.NavigateTo(orderId);
orderPage.GetStatus().Should().Be("Created");
}
[Test]
public void LoginViaApi_InjectTokenToBrowser()
{
// Login via API (faster than UI)
var authClient = new ApiClient("https://api.example.com");
var loginResponse = authClient.Post<LoginResponse>("/auth/login", new {
username = "testuser",
password = "testpass"
});
var token = loginResponse.Data!.Token;
// Inject token into browser
NavigateToBaseUrl();
((IJavaScriptExecutor)Driver).ExecuteScript(
$"localStorage.setItem('token', '{token}');");
Driver.Navigate().Refresh();
// Verify logged in state
var homePage = new HomePage();
homePage.IsUserLoggedIn().Should().BeTrue();
}tests/TestAutomation.Tests/
βββ Tests/
β βββ API/ # Pure API tests
β β βββ SampleApiTests.cs
β β βββ AuthApiTests.cs
β βββ UI/ # Pure UI tests
β β βββ LoginTests.cs
β β βββ SampleTests.cs
β βββ Hybrid/ # Combined API + UI tests
β βββ HybridTestExample.cs
# Run only API tests
dotnet test --filter "Category=API"
# Run only UI tests
dotnet test --filter "Category=UI"
# Run hybrid tests
dotnet test --filter "Category=Hybrid"The framework includes pre-configured GitHub Actions workflows:
- Triggers on push/PR to main/develop
- Supports manual trigger with environment selection
- Multi-browser matrix testing
- Uploads test artifacts
- Runs daily at 2 AM UTC
- Executes regression test suite
- Multi-browser testing
Configure these secrets in your repository:
| Secret | Description |
|---|---|
BASE_URL |
Application base URL |
Use the included Jenkinsfile:
// Trigger build with parameters
// - ENVIRONMENT: Development/Staging/Production
// - BROWSER: Chrome/Firefox/Edge
// - HEADLESS: true/false
// - TEST_FILTER: NUnit filter expression# Example Dockerfile for containerized execution
FROM mcr.microsoft.com/dotnet/sdk:10.0
# Install Chrome
RUN apt-get update && apt-get install -y chromium
WORKDIR /app
COPY . .
RUN dotnet restore
RUN dotnet build
CMD ["dotnet", "test"]The framework supports Selenium Grid for distributed test execution across multiple browsers and machines.
Selenium Grid allows you to:
- Run tests on multiple browsers simultaneously
- Execute tests on remote machines
- Scale test execution horizontally
- Test on different browser versions
A docker-compose.yml is included for easy Grid setup:
# Start Selenium Grid (Hub + Chrome, Firefox, Edge nodes)
docker-compose up -d
# Verify Grid is running
# Open browser: http://localhost:4444/ui
# Run tests against Grid
TEST_AUTO_USE_REMOTE_DRIVER=true \
TEST_AUTO_REMOTE_WEBDRIVER_URL=http://localhost:4444/wd/hub \
dotnet test
# Stop Grid
docker-compose downβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Selenium Grid Hub β
β http://localhost:4444 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β Chrome β β Firefox β β Edge β β
β β Node β β Node β β Node β β
β β (4 slots) β β (4 slots) β β (4 slots) β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export TEST_AUTO_USE_REMOTE_DRIVER=true
export TEST_AUTO_REMOTE_WEBDRIVER_URL=http://localhost:4444/wd/hub
export TEST_AUTO_BROWSER=Chrome
dotnet test{
"TestSettings": {
"UseRemoteDriver": true,
"RemoteWebDriverUrl": "http://localhost:4444/wd/hub",
"Browser": "Chrome"
}
}{
"TestSettings": {
"UseRemoteDriver": true,
"RemoteWebDriverUrl": "http://selenium-grid.company.com:4444/wd/hub"
}
}For simpler setups, use standalone containers:
# Chrome only
docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-chrome:4.25.0
# Firefox only
docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-firefox:4.25.0
# Edge only
docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-edge:4.25.0The framework also works with cloud providers:
| Provider | Remote URL Format |
|---|---|
| BrowserStack | https://USER:KEY@hub-cloud.browserstack.com/wd/hub |
| Sauce Labs | https://USER:KEY@ondemand.saucelabs.com/wd/hub |
| LambdaTest | https://USER:KEY@hub.lambdatest.com/wd/hub |
# Example with BrowserStack
export TEST_AUTO_USE_REMOTE_DRIVER=true
export TEST_AUTO_REMOTE_WEBDRIVER_URL="https://user:key@hub-cloud.browserstack.com/wd/hub"
dotnet testservices:
selenium:
image: selenium/standalone-chrome:4.25.0
ports:
- 4444:4444
options: --shm-size="2g"
steps:
- name: Run tests on Grid
run: dotnet test
env:
TEST_AUTO_USE_REMOTE_DRIVER: true
TEST_AUTO_REMOTE_WEBDRIVER_URL: http://localhost:4444/wd/hubIncrease browser nodes for more parallel capacity:
# Scale Chrome nodes to 5 instances
docker-compose up -d --scale chrome=5
# Scale all browsers
docker-compose up -d --scale chrome=3 --scale firefox=3 --scale edge=2The framework is designed for future MCP (Model Context Protocol) integration to enable AI-assisted testing.
- Test Context Sharing - Share execution state with AI
- Locator Healing - AI-powered locator repair
- Failure Analysis - Automatic root cause analysis
- Test Generation - Generate tests from descriptions
See src/TestAutomation.Framework/MCP/McpIntegrationReadme.md for details.
- β One assertion focus per test
- β Independent tests (no dependencies)
- β Meaningful test names
- β Proper test categorization
- β Clean up test data
- β Single Responsibility Principle
- β Fluent method chaining
- β No assertions in page objects
- β Reusable components
- β Use data-testid attributes
- β Externalize in JSON files
- β Avoid brittle locators
- β Document complex locators
- β Use explicit waits
- β Avoid Thread.Sleep
- β Wait for specific conditions
- β Set reasonable timeouts
- β No hardcoded values
- β Environment-specific configs
- β Secrets in environment variables
- β Sensible defaults
WebDriverException: Cannot find Chrome binary
Solution: Install Chrome or set TEST_AUTO_BROWSER to an installed browser.
NoSuchElementException: Unable to locate element
Solution:
- Verify locator is correct
- Add explicit wait
- Check if element is in iframe
WebDriverTimeoutException: Timed out after X seconds
Solution:
- Increase timeout in settings
- Check network connectivity
- Verify page loads correctly
Tests fail in headless but pass in headed mode
Solution:
- Set window size explicitly
- Check for viewport-dependent elements
- Review console errors
Enable detailed logging:
{
"TestSettings": {
"EnableDetailedLogging": true
}
}- Check the logs in
Logs/folder - Review screenshots in
Screenshots/folder - Check the Extent Report for details
- Enable verbose test output:
dotnet test -v d
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Commit changes:
git commit -am 'Add my feature' - Push to branch:
git push origin feature/my-feature - Submit a Pull Request
- Follow C# naming conventions
- Add XML documentation comments
- Write unit tests for utilities
- Update README for new features
This project is licensed under the MIT License - see the LICENSE file for details.
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Happy Testing! π