Unit testing with xUnit
A unit test is code that checks one small piece of your code automatically. In .NET the common framework is xUnit: [Fact] for a single test, [Theory] with [InlineData] for many inputs, written in the Arrange-Act-Assert pattern and run with dotnet test.
67.1 Why is it used?
- In the demo a 10% coupon on Rs 1000 returns 1000 instead of 900, and the code looks correct in review.
- percent / 100 is int / int, so C# does integer division: 10 / 100 = 0, discount = 0.
- There is no error at all, so the bug can reach production.
- Checking every case by hand after every change is impossible; a unit test does it automatically.
C#
namespace Shop; public static class Discount{ public static decimal Apply( decimal amount, int percent) { if (percent is < 0 or > 100) throw new ArgumentOutOfRangeException( nameof(percent)); var discount = amount * (percent / 100); return amount - discount; }}Output
$ dotnet run check.cs# Discount.Apply(1000m, 10)100067.2 Test project: dotnet new xunit
- A class library Shop holds Discount; Shop.Tests comes from the xunit template.
- The template adds xUnit, its runner and Microsoft.NET.Test.Sdk.
- dotnet add reference lets the tests call the Discount class.
- In xUnit v3 the code for Fact, Theory and Assert stays the same.
Terminal
dotnet new classlib -n Shopdotnet new xunit -n Shop.Testscd Shop.Testsdotnet add reference ..\Shop\Shop.csprojOutput
$ dotnet new classlib -n ShopThe template "Class Library" was created successfully.$ dotnet new xunit -n Shop.TestsThe template "xUnit Test Project" was created successfully.Restore succeeded.$ dotnet add reference ..\Shop\Shop.csprojReference `..\Shop\Shop.csproj` added to the project.67.3 First test: Fact and AAA
- [Fact] marks a test method that takes no input.
- Name = Method_Scenario_Expected (Apply_TenPercent_ReducesAmount), so a failure explains itself.
- Arrange: prepare data. Act: exactly one call. Assert: compare with the expected value.
C#
namespace Shop.Tests; public class DiscountTests{ [Fact] public void Apply_TenPercent_ReducesAmount() { // Arrange var amount = 1000m; // Act var result = Discount.Apply(amount, 10); // Assert Assert.Equal(900m, result); }}67.4 dotnet test: red, then green
- dotnet test builds both projects and runs every test.
- The failure shows Expected 900, Actual 1000 and the line number.
- The fix is one character: 100m makes it decimal division (0.1).
- After the fix the summary says Passed; the test is now a safety net.
Output
$ dotnet test Failed Shop.Tests.DiscountTests.Apply_TenPercent_ReducesAmount [852 ms] Error Message: Assert.Equal() Failure: Values differExpected: 900Actual: 1000 Stack Trace: at ...DiscountTests.cs:line 13Failed! - Failed: 1, Passed: 0, Skipped: 0, Total: 1C#
// Discount.Apply: 100m makes it decimal divisionvar discount = amount * (percent / 100m);return amount - discount;Output
$ dotnet testPassed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1, Duration: 97 ms- Step 1
1.Arrange: prepare input (amount = 1000m)
- Step 2
2.Act: one call, Discount.Apply(amount, 10)
- Step 3
3.Assert: Assert.Equal(900m, result)
- Step 4
4.dotnet test: RED, Expected 900, Actual 1000
- Step 5
5.Fix the code: percent / 100m
- Step 6
6.dotnet test: GREEN, the test now guards against the bug coming back
67.5 Theory: one test, many inputs
- A separate Fact per case is repetition; use [Theory] with one [InlineData] per row.
- Edge cases 0% and 100% are covered too.
- Checkpoint: if one row has a wrong expected value (175), only that case fails: 4 passed, 1 failed, and the output shows the failing row's parameters.
C#
[Theory][InlineData(1000, 10, 900)][InlineData(500, 0, 500)][InlineData(999, 100, 0)][InlineData(200, 25, 150)]public void Apply_ValidPercent_ReturnsNetAmount( decimal amount, int percent, decimal expected){ var result = Discount.Apply(amount, percent); Assert.Equal(expected, result);}Output
$ dotnet test --logger "console;verbosity=normal" Passed ...ReturnsNetAmount(amount: 200, percent: 25, expected: 150) Passed ...ReturnsNetAmount(amount: 999, percent: 100, expected: 0) Passed ...ReturnsNetAmount(amount: 1000, percent: 10, expected: 900) Passed ...ReturnsNetAmount(amount: 500, percent: 0, expected: 500) Passed Shop.Tests.DiscountTests.Apply_TenPercent_ReducesAmountTest Run Successful.Total tests: 5 Passed: 5Output
# last row changed to [InlineData(200, 25, 175)]$ dotnet test Failed ...ReturnsNetAmount(amount: 200, percent: 25, expected: 175) Error Message: Assert.Equal() Failure: Values differExpected: 175Actual: 150.00Failed! - Failed: 1, Passed: 4, Skipped: 0, Total: 5| Feature | [Fact] | [Theory] + [InlineData] |
|---|---|---|
| Input | None | One row of values per InlineData, passed to parameters in order |
| Test cases | One | One per row (each passes/fails separately) |
| Use for | A single behaviour/scenario | Same rule, many inputs and edge cases (0%, 100%) |
| Note | Decimal literals are not allowed in attributes: write ints, xUnit converts |
67.6 Shouldly: readable assertions
- dotnet add package Shouldly.
- result.ShouldBe(900m) reads like a sentence and the failure message includes the variable name.
- Should.Throw<T>(act) checks that 150% throws ArgumentOutOfRangeException (plain xUnit: Assert.Throws).
- FluentAssertions needs a paid licence for commercial use from version 8, so Shouldly is a free option for new projects.
C#
using Shouldly; [Fact]public void Apply_TenPercent_ReducesAmount(){ var result = Discount.Apply(1000m, 10); result.ShouldBe(900m);} [Fact]public void Apply_PercentAbove100_Throws(){ Action act = () => Discount.Apply(1000m, 150); Should.Throw<ArgumentOutOfRangeException>(act);}Output
# buggy Discount$ dotnet test Failed ...DiscountShouldlyTests.Apply_TenPercent_ReducesAmount Error Message: Shouldly.ShouldAssertException : result should be900m but was1000m| Check | xUnit Assert | Shouldly |
|---|---|---|
| Equality | Assert.Equal(900m, result) | result.ShouldBe(900m) |
| Exception | Assert.Throws<ArgumentOutOfRangeException>(...) | Should.Throw<ArgumentOutOfRangeException>(act) |
| Null | Assert.Null(x) | x.ShouldBeNull() |
| Failure message | Expected / Actual | "result should be 900m but was 1000m" |
67.7 Common mistakes
- Assert.Equal(actual, expected): the message is reversed (Expected 1000, Actual 900); the analyzer warns xUnit2000.
- Testing many behaviours in one test, or unclear names like Test1.
- Unit tests that depend on a database, the network or the clock: slow and flaky.
- Believing 100% coverage means bug-free: coverage shows lines that ran, not results that were checked; a test without Assert still adds coverage.
- Thinking tests slow you down: after every refactor they give confidence in seconds.
C#
// Wrong: actual first -> message reversedvar result = Discount.Apply(1000m, 10);Assert.Equal(result, 900m);// Expected: 1000// Actual: 900// warning xUnit2000: ... Swap the parameter values. // Right: expected first, then actualAssert.Equal(900m, result);// Expected: 900// Actual: 100067.8 Interview tips
- "I use xUnit: Fact for one test, Theory with InlineData for many data sets."
- Every test follows AAA and is named Method_Scenario_Expected.
- Expected value first in Assert.Equal.
- Keep unit tests fast and independent: no DB, network or clock.
- Assertions: built-in Assert or Shouldly; newer FluentAssertions versions are paid for commercial use.