How to Use xUnit in C#: Simple Guide with Examples
To use
xUnit in C#, install the xunit and xunit.runner.visualstudio NuGet packages, then create test classes with methods marked by the [Fact] attribute. Run tests using Visual Studio Test Explorer or the dotnet test command.Syntax
In xUnit, you write test methods inside a public class. Each test method is marked with the [Fact] attribute to indicate it is a test. Use assertions like Assert.Equal() to check expected results.
Key parts:
[Fact]: Marks a method as a test.- Test method: A public method with no parameters.
- Assertions: Methods to verify test outcomes.
csharp
using Xunit; public class CalculatorTests { [Fact] public void Add_TwoNumbers_ReturnsSum() { int a = 2; int b = 3; int result = a + b; Assert.Equal(5, result); } }
Example
This example shows a simple test class for a calculator method. It tests that adding two numbers returns the correct sum.
csharp
using Xunit; public class Calculator { public int Add(int x, int y) => x + y; } public class CalculatorTests { [Fact] public void Add_ReturnsCorrectSum() { var calculator = new Calculator(); int result = calculator.Add(4, 5); Assert.Equal(9, result); } }
Output
Test Passed
Common Pitfalls
Common mistakes when using xUnit include:
- Not marking test methods with
[Fact], so tests are not discovered. - Writing test methods with parameters (xUnit requires parameterless
[Fact]methods). - Forgetting to install the
xunit.runner.visualstudiopackage to run tests in Visual Studio. - Using
Assertmethods incorrectly, such as mixing expected and actual values.
csharp
using Xunit; public class WrongTests { // This test will NOT run because it lacks [Fact] public void TestWithoutFact() { Assert.True(true); } // This test will NOT run because it has parameters [Fact] public void TestWithParameters(int x) { Assert.True(x > 0); } } // Correct usage: public class CorrectTests { [Fact] public void TestRuns() { Assert.True(true); } }
Quick Reference
- [Fact]: Marks a test method.
- Assert.Equal(expected, actual): Checks if values are equal.
- Assert.True(condition): Checks if condition is true.
- dotnet test: Runs tests from command line.
- Install
xunitandxunit.runner.visualstudioNuGet packages to enable testing.
Key Takeaways
Install xUnit and its runner packages to enable testing in C# projects.
Mark test methods with [Fact] and keep them parameterless for discovery.
Use Assert methods to verify expected outcomes in tests.
Run tests using Visual Studio Test Explorer or the dotnet test command.
Avoid common mistakes like missing [Fact] or incorrect Assert usage.