C# Unit Testing with xUnit — Complete Beginner Guide
Learning Objectives
- Create an xUnit test project with the CLI
- Write and run unit tests with assertions
- Organize test classes and naming
- Use theory data for parameterized tests
- Adopt habits that keep tests useful
Why Unit Tests Matter
Unit tests verify small pieces of logic in isolation. They catch regressions early, document expected behavior, and give you confidence to refactor. C# developers commonly use xUnit, NUnit, or MSTest; this lesson focuses on xUnit.
Creating a Test Project
From your terminal, create a companion test project:
dotnet new xunit -n MyApp.Tests
cd MyApp.Tests
dotnet new sln -n solution
dotnet sln add ../MyApp/MyApp.csproj
dotnet add reference ../MyApp/MyApp.csproj
Adjust folder names to match your solution. The key steps are create tests, reference the code under test, then restore packages.
Project layout
MyApp.Tests/
UnitTest1.cs
MyApp.Tests.csproj
The generated test file gives you a starting template.
Your First Test
Replace the sample with a focused test:
namespace MyApp.Tests;
public class CalculatorTests
{
[Fact]
public void Add_TwoNumbers_ReturnsSum()
{
int result = 2 + 3;
Assert.Equal(5, result);
}
}
Fact marks a test method. Assert.Equal checks the expected value against the actual value.
Testing Real Code
Move logic into your app project, then test it.
public class Calculator
{
public int Add(int a, int b) => a + b;
}
public class CalculatorTests
{
[Fact]
public void Add_PositiveValues_ReturnsSum()
{
var calc = new Calculator();
int result = calc.Add(4, 5);
Assert.Equal(9, result);
}
}
Tests reference the production type directly so failures point to real behavior.
Common Assertions
| Assertion | Purpose |
|---|---|
| Equal | Values are equal |
| NotEqual | Values differ |
| True or False | Boolean expectations |
| Throws | Exception expected |
| Contains | Collection or string membership |
[Fact]
public void Check_Behaviors()
{
Assert.Equal("ADA", "ada".ToUpper());
Assert.True(10 > 5);
Assert.Contains("dot", "dotnet");
Assert.NotEqual(1, 2);
}
For exceptions, write a dedicated test:
[Fact]
public void Parse_Invalid_ThrowsFormat()
{
Assert.Throws<FormatException>(() => int.Parse("abc"));
}
Theory for Multiple Cases
Theory lets one test method cover many inputs.
public class ValidatorTests
{
[Theory]
[InlineData(0, false)]
[InlineData(1, true)]
[InlineData(-2, false)]
public void IsPositive_ChecksValue(int value, bool expected)
{
bool actual = value > 0;
Assert.Equal(expected, actual);
}
}
InlineData supplies row data without extra classes.
Running Tests
dotnet test
The CLI discovers Fact and Theory methods, runs them, and prints a summary. Failing tests show expected versus actual values, which guides your fix.
Filtering tests
dotnet test --filter "FullyQualifiedName~Calculator"
Filters speed up large suites while you iterate.
Naming and Structure
- Name tests as behavior expectations, such as Withdraw_InsufficientFunds_Throws
- Group tests by the class you are verifying
- Keep one logical assertion story per test when practical
- Avoid depending on test order
- Prefer deterministic tests over sleep based timing checks
What Makes a Good Unit Test
| Quality | Why it matters |
|---|---|
| Isolated | No hidden network or file dependencies |
| Repeatable | Same result every run |
| Fast | Encourages frequent runs |
| Clear failure | Names and asserts explain breakage |
| Focused | One behavior per test where possible |
Use fakes or simple stub collaborators when a unit needs boundaries.
Common Mistakes
Testing the framework only
Asserting that string concatenation works adds little value. Test your rules and branches.
Duplicating implementation in assertions
If your test restates the same complex formula, bugs can appear in both places. Use clear known cases.
Ignoring failures in CI
A red build that everyone skips becomes noise. Fix or quarantine deliberately.
Giant test methods
Small tests are easier to read and pinpoint failures.
Key Takeaways
💡
- dotnet new xunit scaffolds a ready to run test project
- Fact marks simple tests; Theory supports parameterized cases
- Assert APIs communicate expectations clearly
- dotnet test runs and reports your suite from the CLI
- Write isolated, fast, behavior focused tests with descriptive names
Practice Questions
- Which CLI command creates an xUnit project?
- What attribute marks a parameterized test with InlineData?
- How do you assert that parsing abc throws FormatException?
- Why should unit tests avoid external network calls?
- Add a Calculator.Subtract method and write two tests covering positive and negative results.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions