A comprehensive test automation framework built with C#, Selenium WebDriver, Reqnroll (BDD - SpecFlow successor), and NUnit for both UI and REST API testing.
- Features
- Prerequisites
- Project Structure
- Getting Started
- Configuration
- Writing Tests
- Running Tests
- Reporting
- CI/CD Integration
- Best Practices
- Troubleshooting
- BDD with Reqnroll: Write tests in Gherkin syntax for better collaboration (Reqnroll is the community-maintained successor to SpecFlow, supporting .NET 8+)
- Selenium WebDriver: Cross-browser UI testing (Chrome, Firefox, Edge, Safari)
- REST API Testing: Built-in support for API testing with RestSharp
- JSON-based Locators: Simplified, maintainable element locators
- Page Object Model: Clean separation of test logic and page interactions
- Multiple Environments: Easy switching between Dev, Staging, Production
- Parallel Execution: Thread-safe design for parallel test execution
- Comprehensive Reporting: Extent Reports and Allure integration
- CI/CD Ready: GitHub Actions and Jenkins configurations included
- Logging: Structured logging with Serilog
- .NET 10 SDK - Download
- IDE: Visual Studio 2022, VS Code, or JetBrains Rider
- Browser: Chrome, Firefox, Edge, or Safari
dotnet --version
# Should output: 10.x.xCS-Selenium-SpecFlow/
├── .github/
│ └── workflows/
│ └── test.yml # GitHub Actions workflow
├── Config/
│ ├── appsettings.json # Base configuration
│ ├── appsettings.Development.json
│ ├── appsettings.Staging.json
│ └── appsettings.Production.json
├── Core/
│ ├── Api/
│ │ ├── ApiClient.cs # REST API client
│ │ └── ApiAssertions.cs # Fluent API assertions
│ ├── Configuration/
│ │ └── ConfigurationManager.cs
│ ├── Drivers/
│ │ ├── DriverFactory.cs # WebDriver factory
│ │ └── DriverManager.cs # Thread-safe driver management
│ ├── Locators/
│ │ ├── LocatorModel.cs # Locator data models
│ │ └── LocatorReader.cs # JSON locator reader
│ ├── Logging/
│ │ └── Logger.cs # Serilog wrapper
│ ├── Pages/
│ │ └── BasePage.cs # Base page object
│ ├── Reporting/
│ │ └── ExtentReportManager.cs
│ └── Utilities/
│ ├── TestDataReader.cs # Test data utilities
│ └── WaitHelper.cs # Wait utilities
├── Features/
│ ├── Login.feature # UI test scenarios
│ └── ApiTests.feature # API test scenarios
├── Hooks/
│ └── TestHooks.cs # SpecFlow lifecycle hooks
├── Locators/
│ ├── LoginPage.json # Login page locators
│ └── HomePage.json # Home page locators
├── Pages/
│ ├── LoginPage.cs # Login page object
│ └── HomePage.cs # Home page object
├── StepDefinitions/
│ ├── CommonSteps.cs # Common step definitions
│ ├── LoginSteps.cs # Login step definitions
│ └── ApiSteps.cs # API step definitions
├── TestData/
│ └── users.json # Test data files
├── .env.example # Environment variables template
├── .gitignore
├── CS-Selenium-SpecFlow.csproj
├── CS-Selenium-SpecFlow.sln
├── Jenkinsfile # Jenkins pipeline
├── README.md
└── reqnroll.json # Reqnroll configuration
git clone https://github.com/amitbad/CS-Selenium-SpecFlow.git
cd CS-Selenium-SpecFlowdotnet restoredotnet buildCopy the environment template and update values:
cp .env.example .envEdit .env with your configuration:
TEST_ENVIRONMENT=Development
BROWSER_TYPE=Chrome
BROWSER_HEADLESS=false
APP_BASE_URL=https://your-app.com
API_BASE_URL=https://api.your-app.com
TEST_USERNAME=your-test-user
TEST_PASSWORD=your-test-passworddotnet testConfiguration is loaded in the following order (later sources override earlier):
Config/appsettings.json(base settings)Config/appsettings.{Environment}.json(environment-specific)- Environment variables (highest priority)
| Variable | Description | Default |
|---|---|---|
TEST_ENVIRONMENT |
Environment name (Development/Staging/Production) | Development |
BROWSER_TYPE |
Browser to use (Chrome/Firefox/Edge/Safari) | Chrome |
BROWSER_HEADLESS |
Run browser in headless mode | false |
APP_BASE_URL |
Application base URL | https://example.com |
API_BASE_URL |
API base URL | https://api.example.com |
TEST_USERNAME |
Test user username | - |
TEST_PASSWORD |
Test user password | - |
API_KEY |
API key for authentication | - |
Edit Config/appsettings.json:
{
"Browser": {
"Type": "Chrome",
"Headless": false,
"ImplicitWait": 10,
"ExplicitWait": 30,
"PageLoadTimeout": 60,
"WindowSize": {
"Width": 1920,
"Height": 1080
}
}
}Create feature files in the Features/ directory:
@ui @login
Feature: Login Functionality
@smoke @positive
Scenario: Successful login with valid credentials
Given I am on the login page
When I enter username "testuser"
And I enter password "testpassword"
And I click the login button
Then I should be logged in successfullyCreate locator files in the Locators/ directory:
{
"pageName": "LoginPage",
"pageUrl": "/login",
"locators": {
"usernameInput": {
"type": "id",
"value": "username",
"description": "Username input field"
},
"passwordInput": {
"type": "css",
"value": "input[type='password']",
"description": "Password input field"
},
"loginButton": {
"type": "xpath",
"value": "//button[@type='submit']",
"description": "Login submit button"
}
}
}Supported Locator Types:
id- By IDname- By name attributeclassNameorclass- By class nametagNameortag- By tag namelinkTextorlink- By link textpartialLinkTextorpartialLink- By partial link textcssSelectororcss- By CSS selectorxpath- By XPath
Create page objects in the Pages/ directory:
using CS_Selenium_SpecFlow.Core.Pages;
public class LoginPage : BasePage
{
protected override string PageName => "LoginPage";
public void EnterUsername(string username)
{
Type("usernameInput", username);
}
public void EnterPassword(string password)
{
Type("passwordInput", password);
}
public void ClickLoginButton()
{
Click("loginButton");
}
public void Login(string username, string password)
{
EnterUsername(username);
EnterPassword(password);
ClickLoginButton();
}
}Create step definitions in the StepDefinitions/ directory:
using TechTalk.SpecFlow;
using NUnit.Framework;
[Binding]
public class LoginSteps
{
private readonly LoginPage _loginPage = new();
[Given(@"I am on the login page")]
public void GivenIAmOnTheLoginPage()
{
_loginPage.NavigateToPage();
}
[When(@"I enter username ""(.*)""")]
public void WhenIEnterUsername(string username)
{
_loginPage.EnterUsername(username);
}
[Then(@"I should be logged in successfully")]
public void ThenIShouldBeLoggedInSuccessfully()
{
Assert.That(_homePage.IsUserLoggedIn(), Is.True);
}
}@api
Feature: REST API Testing
Scenario: Get user by ID
Given I have an API client
When I send a GET request to "/users/1"
Then the response status code should be 200
And the response JSON property "id" should be "1"dotnet test# Run smoke tests
dotnet test --filter "Category=smoke"
# Run UI tests only
dotnet test --filter "Category=ui"
# Run API tests only
dotnet test --filter "Category=api"
# Run multiple categories
dotnet test --filter "Category=smoke|Category=regression"dotnet test --filter "FullyQualifiedName~Login"BROWSER_TYPE=Firefox dotnet testBROWSER_HEADLESS=true dotnet testTEST_ENVIRONMENT=Staging dotnet testdotnet test --parallelReports are automatically generated in Reports/ExtentReports/ after test execution.
Open the HTML report in a browser to view:
- Test execution summary
- Pass/Fail statistics
- Screenshots on failure
- Step-by-step execution details
-
Install Allure CLI:
# macOS brew install allure # Windows (Scoop) scoop install allure
-
Generate and open report:
allure serve allure-results
Screenshots are automatically captured on test failure and saved to Reports/Screenshots/.
GitHub Actions is a CI/CD service built into GitHub. If you're new to it, follow these steps:
- Your code must be hosted on GitHub (public or private repository)
- The workflow file
.github/workflows/test.ymlis already included in this framework
# Initialize git (if not already done)
git init
# Add all files
git add .
# Commit
git commit -m "Initial commit - Test automation framework"
# Add your GitHub repository as remote
git remote add origin https://github.com/YOUR_USERNAME/YOUR_REPO_NAME.git
# Push to GitHub
git push -u origin mainSecrets store sensitive data like passwords and API keys securely.
- Go to your repository on GitHub
- Click Settings (tab at the top)
- In the left sidebar, click Secrets and variables → Actions
- Click New repository secret
- Add each secret one by one:
| Secret Name | Description | Example Value |
|---|---|---|
APP_BASE_URL |
Your application URL | https://myapp.com |
API_BASE_URL |
Your API URL | https://api.myapp.com |
TEST_USERNAME |
Test user login | testuser@example.com |
TEST_PASSWORD |
Test user password | SecurePassword123 |
API_KEY |
API key (if needed) | sk-abc123... |
Note: Secrets are encrypted and never exposed in logs.
Ensure .github/workflows/test.yml exists in your repository. It's already created by this framework.
The workflow runs automatically on:
- Push to
mainordevelopbranches - Pull requests to
mainordevelop
To run manually:
- Go to your repository on GitHub
- Click Actions tab
- Select Test Automation workflow from the left
- Click Run workflow button (dropdown on right)
- Select options:
- Environment: Development/Staging/Production
- Browser: Chrome/Firefox/Edge
- Tags: (optional) e.g.,
@smoke
- Click Run workflow
- Go to Actions tab
- Click on the running/completed workflow
- View logs, download artifacts (test results, screenshots)
The included workflow supports:
- Multi-browser testing: Chrome, Firefox, Edge
- Environment selection: Dev, Staging, Production
- Tag filtering: Run specific test categories
- Artifacts: Test results, screenshots, Allure reports
- Allure Reports: Auto-published to GitHub Pages
- Go to Actions → Test Automation → Run workflow
- Set Tags to
@smoke - Run workflow
Workflow not running?
- Check if
.github/workflows/test.ymlexists - Verify branch name matches trigger conditions
Secrets not working?
- Secret names are case-sensitive
- Secrets are only available in the repository where they're defined
Tests failing in CI but passing locally?
- CI runs in headless mode by default
- Check if all required secrets are configured
- Review the workflow logs for detailed errors
If you can't use GitHub Actions, you can still run tests:
# Set environment variables
export APP_BASE_URL="https://myapp.com"
export TEST_USERNAME="testuser"
export TEST_PASSWORD="password"
# Run tests
dotnet testThe Jenkinsfile is already included. See Jenkins section below.
Just run these commands in your CI pipeline:
dotnet restore
dotnet build --configuration Release
dotnet test --configuration Release --logger "trx;LogFileName=results.trx"-
Install required plugins:
- .NET SDK Support
- Allure Jenkins Plugin
- MSTest Plugin
-
Configure credentials in Jenkins:
app-base-urlapi-base-urltest-usernametest-passwordapi-key
-
Create a Pipeline job pointing to the
Jenkinsfile
Create azure-pipelines.yml:
trigger:
- main
pool:
vmImage: 'ubuntu-latest'
steps:
- task: UseDotNet@2
inputs:
version: '10.x'
- script: dotnet restore
displayName: 'Restore'
- script: dotnet build --configuration Release
displayName: 'Build'
- script: dotnet test --configuration Release --logger trx
displayName: 'Test'
env:
APP_BASE_URL: $(APP_BASE_URL)
TEST_USERNAME: $(TEST_USERNAME)
TEST_PASSWORD: $(TEST_PASSWORD)
- task: PublishTestResults@2
inputs:
testResultsFormat: 'VSTest'
testResultsFiles: '**/*.trx'- Prefer stable locators: ID > Name > CSS > XPath
- Avoid dynamic attributes: Don't use auto-generated IDs
- Use data attributes:
data-testid="login-button" - Keep locators in JSON files: Easy maintenance and reuse
- One page = One class: Keep page objects focused
- Encapsulate actions: Methods should represent user actions
- Return page objects: For fluent chaining
- No assertions in page objects: Keep assertions in step definitions
- Externalize test data: Use JSON files in
TestData/ - Use environment variables: For sensitive data
- Data-driven tests: Use Scenario Outlines with Examples
- Thread-safe design: Use ThreadLocal for driver instances
- Independent tests: Tests should not depend on each other
- Unique test data: Avoid data conflicts between parallel tests
The framework includes comprehensive error handling throughout:
- Driver not initialized: Clear message if you try to use driver before calling
InitializeDriver() - Browser not found: Helpful error if browser isn't installed
- Navigation failures: Detailed errors with URL that failed
- Missing locator file: Error specifies which JSON file is missing
- Missing element in JSON: Error tells you which element isn't defined
- Element not found on page: Timeout error with element name and page
- Missing base URL: Clear message to configure
API_BASE_URL - Request failures: Logs full request details and error
- Deserialization errors: Specifies the type that failed to deserialize
❌ Element 'loginButton' not found on page 'LoginPage'. Check if the locator is correct in LoginPage.json
❌ Base URL is not configured. Set APP_BASE_URL environment variable or configure in appsettings.json
❌ Failed to initialize Chrome browser. Ensure the browser is installed.
❌ Locator file not found: /path/to/Locators/LoginPage.json
All errors are logged with full stack traces to Logs/ directory. Enable debug logging for more details:
{
"Logging": {
"Level": "Debug"
}
}1. WebDriver not found
# WebDriverManager handles this automatically
# If issues persist, ensure Chrome/Firefox is installed2. Element not found
# Increase explicit wait time in appsettings.json
# Check if locator is correct in JSON file
# Verify element is visible and not in iframe3. Tests fail in headless mode
# Some elements may behave differently in headless
# Try increasing window size
# Check for JavaScript errors in console4. Configuration not loading
# Ensure appsettings.json is copied to output
# Check TEST_ENVIRONMENT variable is set correctlyEnable verbose logging:
{
"Logging": {
"Level": "Debug"
}
}- Check the logs in
Logs/directory - Review screenshots in
Reports/Screenshots/ - Enable debug logging for more details
- Fork the repository
- Create a feature branch
- Make your changes
- Run tests locally
- Submit a pull request
This project is licensed under the MIT License.
Happy Testing!