Practical 20: Unit Testing with NUnit and Load Testing with JMeter
Aim
Part A: Write a .NET login and logout class. Use NUnit to check valid input, wrong passwords, empty input and account lockout.
Part B: Use JMeter to send requests like several users at once. Increase the user count and compare response time, completed requests and errors.
Part A – Unit testing with NUnit
Theory
NUnit is an open-source unit-testing framework for .NET (C#, VB.NET, F#), ported originally from JUnit.
The AuthService class is a smart door lock. Positive tests: the right key opens it, and locking it again works. Negative tests: a wrong key, an unknown person, an empty key – the door must stay shut, and after three wrong tries it must lock itself. NUnit runs all these checks automatically.
| NUnit attribute | Purpose |
|---|---|
[TestFixture] |
Marks a class containing tests |
[Test] |
A test method |
[SetUp] / [TearDown] |
Run before / after each test |
[OneTimeSetUp] / [OneTimeTearDown] |
Run once per fixture |
[TestCase(args)] |
Parameterised test with inline data |
[TestCaseSource] |
Data from a method/field |
[Ignore("reason")], [Category("smoke")], [Order(n)] |
Skip, group, order |
NUnit uses the constraint model: Assert.That(actual, Is.EqualTo(expected)), plus Is.True, Is.False, Is.Null, Does.Contain, Throws.TypeOf<…>(), Assert.Throws<T>(() => …).
| JUnit 4 | NUnit 3/4 |
|---|---|
@Test |
[Test] |
@Before / @After |
[SetUp] / [TearDown] |
@BeforeClass / @AfterClass |
[OneTimeSetUp] / [OneTimeTearDown] |
@RunWith(Parameterized) |
[TestCase(…)] |
assertEquals(e, a) |
Assert.That(a, Is.EqualTo(e)) |
Requirements
- Visual Studio 2022 (Community) with the .NET desktop development workload, or the .NET 8 SDK (Software Development Kit) + VS Code.
- NuGet packages:
NUnit,NUnit3TestAdapter,Microsoft.NET.Test.Sdk.
Procedure
- Create a Class Library project
AuthSystem(.NET 8). - Add a NUnit Test Project
AuthSystem.Tests(File → New → Project → NUnit Test Project) and add a project reference toAuthSystem.
dotnet new classlib -n AuthSystem
dotnet new nunit -n AuthSystem.Tests
dotnet add AuthSystem.Tests reference AuthSystem
- Implement the class, write the tests, and run them from Test → Test Explorer → Run All (or
dotnet test).
AuthService.cs
using System;
using System.Collections.Generic;
namespace AuthSystem
{
public class AuthService
{
private readonly Dictionary<string, string> _users = new()
{
["student"] = "Pass@123",
["admin"] = "Admin@2026"
};
private readonly Dictionary<string, int> _failedAttempts = new();
private const int MaxAttempts = 3;
public string? CurrentUser { get; private set; }
public bool IsLoggedIn => CurrentUser != null;
public bool Login(string username, string password)
{
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
throw new ArgumentException("Username and password are required");
if (IsLocked(username))
throw new InvalidOperationException("Account locked");
if (_users.TryGetValue(username, out var stored) && stored == password)
{
CurrentUser = username;
_failedAttempts[username] = 0;
return true;
}
_failedAttempts[username] = _failedAttempts.GetValueOrDefault(username) + 1;
return false;
}
public void Logout()
{
if (!IsLoggedIn) throw new InvalidOperationException("No user is logged in");
CurrentUser = null;
}
public bool IsLocked(string username) =>
_failedAttempts.GetValueOrDefault(username) >= MaxAttempts;
}
}
AuthServiceTests.cs
using System;
using NUnit.Framework;
using AuthSystem;
namespace AuthSystem.Tests
{
[TestFixture]
public class AuthServiceTests
{
private AuthService _auth = null!;
[SetUp]
public void SetUp() => _auth = new AuthService();
// ---------- positive scenarios ----------
[Test]
public void Login_WithValidCredentials_ReturnsTrue()
{
bool result = _auth.Login("student", "Pass@123");
Assert.That(result, Is.True);
Assert.That(_auth.IsLoggedIn, Is.True);
Assert.That(_auth.CurrentUser, Is.EqualTo("student"));
}
[Test]
public void Logout_AfterLogin_ClearsCurrentUser()
{
_auth.Login("admin", "Admin@2026");
_auth.Logout();
Assert.That(_auth.IsLoggedIn, Is.False);
Assert.That(_auth.CurrentUser, Is.Null);
}
// ---------- negative scenarios ----------
[TestCase("student", "wrong")]
[TestCase("nobody", "Pass@123")]
[TestCase("STUDENT", "Pass@123")] // usernames are case-sensitive
public void Login_WithInvalidCredentials_ReturnsFalse(string user, string pass)
{
Assert.That(_auth.Login(user, pass), Is.False);
Assert.That(_auth.IsLoggedIn, Is.False);
}
[TestCase("", "Pass@123")]
[TestCase("student", "")]
[TestCase(" ", " ")]
public void Login_WithEmptyInput_ThrowsArgumentException(string user, string pass)
{
var ex = Assert.Throws<ArgumentException>(() => _auth.Login(user, pass));
Assert.That(ex!.Message, Does.Contain("required"));
}
[Test]
public void Login_AfterThreeFailures_LocksAccount()
{
for (int i = 0; i < 3; i++) _auth.Login("student", "bad");
Assert.That(_auth.IsLocked("student"), Is.True);
Assert.Throws<InvalidOperationException>(() => _auth.Login("student", "Pass@123"));
}
[Test]
public void Logout_WithoutLogin_Throws()
{
Assert.Throws<InvalidOperationException>(() => _auth.Logout());
}
}
}
Output (Test Explorer / dotnet test)
Passed! - Failed: 0, Passed: 10, Skipped: 0, Total: 10, Duration: 48 ms - AuthSystem.Tests.dll (net8.0)
✔ Login_WithValidCredentials_ReturnsTrue
✔ Logout_AfterLogin_ClearsCurrentUser
✔ Login_WithInvalidCredentials_ReturnsFalse("student","wrong")
✔ Login_WithInvalidCredentials_ReturnsFalse("nobody","Pass@123")
✔ Login_WithInvalidCredentials_ReturnsFalse("STUDENT","Pass@123")
✔ Login_WithEmptyInput_ThrowsArgumentException("","Pass@123")
✔ Login_WithEmptyInput_ThrowsArgumentException("student","")
✔ Login_WithEmptyInput_ThrowsArgumentException(" "," ")
✔ Login_AfterThreeFailures_LocksAccount
✔ Logout_WithoutLogin_Throws
Virtual lab · Testing Tools · 35 min
Unit-test an authentication class with NUnit in Visual Studio
Create a .NET 8 class library and an NUnit test project in Visual Studio 2022, wire the project reference, implement AuthService, and verify valid, invalid, empty-input and lock-out scenarios in Test Explorer and with dotnet test.
Part B – Load testing with Apache JMeter
Theory
Performance testing checks speed, scalability and stability under load.
| Type | Goal |
|---|---|
| Load test | Behaviour under expected concurrent users |
| Stress test | Find the breaking point beyond normal load |
| Spike test | Sudden large increase in users |
| Endurance (soak) test | Stability over a long period (memory leaks) |
| Scalability test | How capacity grows with added resources |
Apache JMeter is an open-source Java tool that simulates many concurrent users sending requests (HTTP (Hypertext Transfer Protocol), REST (Representational State Transfer), SOAP (originally Simple Object Access Protocol), JDBC (Java Database Connectivity), FTP (File Transfer Protocol)…) and measures performance.
Elements of a JMeter test plan
flowchart TB
TP[Test Plan] --> TG[Thread Group<br/>users · ramp-up · loops]
TG --> CFG[Config elements<br/>HTTP Request Defaults · Cookie Manager · CSV Data Set]
TG --> S1[Sampler: HTTP GET /]
TG --> S2[Sampler: HTTP GET /products]
TG --> S3[Sampler: HTTP POST /login]
TG --> TM[Timer – think time]
S1 & S2 & S3 --> AS[Assertions<br/>Response code 200 · Duration]
TG --> L[Listeners<br/>Summary Report · Aggregate Report ·<br/>View Results Tree · Graph]
| Element | Purpose |
|---|---|
| Thread Group | Number of threads (virtual users), ramp-up period (time to start all users), loop count or duration |
| Sampler | The request to send – HTTP Request |
| Config element | HTTP Request Defaults (server, port), HTTP Cookie Manager (sessions), CSV (Comma-Separated Values) Data Set Config (test data) |
| Timer | Think time between requests – Constant Timer, Uniform Random Timer |
| Assertion | Check responses – Response Assertion, Duration Assertion |
| Listener | Collect and display results – View Results Tree, Summary Report, Aggregate Report, Graph Results |
Key metrics
| Metric | Meaning |
|---|---|
| Samples | Number of requests |
| Average / Median | Mean / middle response time (ms) |
| 90th / 95th / 99th percentile | Response time that 90/95/99 % of requests were faster than |
| Min / Max | Fastest / slowest response |
| Error % | Failed requests (HTTP errors or failed assertions) |
| Throughput | Requests per second the server handled |
| Received / Sent KB/sec | Network traffic |
Requirements
- JDK (Java Development Kit) 8+ and Apache JMeter 5.6 (
apache-jmeter-5.6.3.zip). - AUT (Application Under Test): VLP Demo Store (
demo.virtuallp.test) with pages/,/products,/products/42,/login(POST).
Procedure
- Extract JMeter and start the GUI (Graphical User Interface):
bin\jmeter.bat(Windows) orbin/jmeter.sh. - Test Plan → rename
DemoStore Load Test. - Right-click Test Plan → Add → Threads (Users) → Thread Group:
- Number of threads 50, Ramp-up 10 s, Loop count 5.
- Add Config Element → HTTP Request Defaults: Protocol
https, Serverdemo.virtuallp.test. - Add Config Element → HTTP Cookie Manager.
- Add Sampler → HTTP Request (×4):
Home– GET/Product list– GET/productsProduct detail– GET/products/42Login– POST/loginwith parametersusername=student,password=Pass@123
- Add Timer → Uniform Random Timer (constant delay 1000 ms, random 2000 ms) to simulate think time.
- Add Assertions → Response Assertion (Response Code Equals
200) and Duration Assertion (2000ms). - Add Listener → View Results Tree, Summary Report and Aggregate Report.
- Save as
DemoStoreLoad.jmxand click Start (▶). Watch the active thread count in the top-right corner. - Repeat with 100 and 200 threads to observe scaling.
- For real load tests use non-GUI mode and generate an HTML (Hypertext Markup Language) dashboard:
jmeter -n -t DemoStoreLoad.jmx -l results.jtl -e -o report/
Virtual lab · Testing Tools · 35 min
Load-test the VLP Demo Store with Apache JMeter
Build a JMeter test plan with a thread group, HTTP defaults, four samplers, think time, assertions and listeners, then run it with 50, 100 and 200 users and find the bottleneck from throughput, percentiles and error rate.
Output – Summary Report (50 users)
Label # Samples Average Min Max Std.Dev Error % Throughput KB/sec
Home 250 182 96 611 74 0.00% 11.8/sec 142.6
Product list 250 264 131 932 118 0.00% 11.7/sec 305.1
Product detail 250 221 104 780 96 0.00% 11.7/sec 188.3
Login 250 398 187 1874 211 0.40% 11.6/sec 21.9
TOTAL 1000 266 96 1874 159 0.10% 46.3/sec 656.4
Analysis of results across loads
| Users | Avg (ms) | 90th % (ms) | Throughput (req/s) | Error % |
|---|---|---|---|---|
| 50 | 266 | 470 | 46.3 | 0.1 |
| 100 | 412 | 820 | 88.9 | 0.3 |
| 200 | 1,940 | 4,300 | 94.1 | 6.8 |
From 50 to 100 users, completed requests rise from 46 to 89 per second. At 200 users, the rate rises only to 94, while delays and errors grow. In this sample, adding users has reached a capacity limit.
Observations – bottlenecks
- Up to 100 users throughput almost doubles and response time grows modestly – the system scales.
- At 200 users throughput plateaus (~94 req/s) while average response time jumps to ~1.9 s and errors rise to 6.8 % – a capacity limit.
- The Login request is the slowest and the first to fail (Duration Assertion) – it performs password hashing and database writes; it is the bottleneck.
- Suggested optimisations: database indexing / connection pooling, caching product pages, horizontal scaling of web servers behind a load balancer (auto-scaling in the cloud), and a CDN (Content Delivery Network) for static assets.
Conclusion
For Part A, check the NUnit results for valid and invalid login actions. For Part B, compare JMeter results at each user count. In the sample results, delays and errors grow beyond about 100 users. Use your own measured results to find the slow part.
Viva questions
- What is NUnit? Explain
[TestFixture],[Test],[SetUp]and[TestCase]. .NET's unit-testing framework;[TestFixture]marks a test class,[Test]a test method,[SetUp]runs before each test,[TestCase(...)]runs a test with given arguments. - How are exceptions tested in NUnit?
Assert.Throws<ArgumentException>(() => auth.Login("", "x")). - Compare JUnit and NUnit annotations.
@Test↔[Test],@Before↔[SetUp],@After↔[TearDown],@BeforeClass↔[OneTimeSetUp], parameterised ↔[TestCase]. - Differentiate load, stress, spike and endurance testing. Load = expected users; stress = beyond the limit; spike = sudden jump; endurance (soak) = normal load for a long time.
- Explain the elements of a JMeter test plan. Thread Group (users), Samplers (requests), Config elements, Timers (think time), Assertions (checks) and Listeners (reports).
- What is ramp-up period? If 50 threads have a 10 s ramp-up, how often does a new user start? The time to start all threads; 10 ÷ 50 = a new user every 0.2 s.
- Define throughput, average response time, 90th percentile and error %. Requests per second; mean time per request; the time within which 90 % of requests finished; percentage of failed requests.
- Why should load tests be run in non-GUI mode? The GUI itself uses lots of CPU (Central Processing Unit) and memory and distorts results;
jmeter -n -t plan.jmx -l results.jtlis lighter. - How do you identify a bottleneck from JMeter results? Find where throughput stops rising while response time and errors climb, and which request has the highest p90/errors (here Login).
Practise this topic
Hands-on virtual labs
Apply what you just read in a realistic, guided simulation. Free with a verified account.
Create a free account to track your progress and unlock virtual labs.