Theory vs Fact attribute — C# XUnit Testing

Ponganesh P
2 min readFeb 29, 2024

--

.net banner

[Fact]

The Fact attribute is used to mark a method as a test method. It signifies that the method represents a fact that should always be true.

  • A test marked with the Fact attribute represents a single test case.
  • If the test method throws an exception or fails an assertion, the test is considered failed.
using Xunit;

public class MathTests
{
[Fact]
public void Add_TwoPlusTwo_ReturnsFour()
{
// Arrange
var calculator = new Calculator();

// Act
var result = calculator.Add(2, 2);

// Assert
Assert.Equal(4, result);
}
}

[Theory]

  • The Theory attribute is used to define a parametrized test. It allows testing multiple inputs against the same test logic.
  • You provide one or more data sources (via attributes like InlineData, MemberData, etc.) to supply the test with different input values.
  • Each set of input values is treated as a separate test case.
  • If any of the test cases fail, the entire theory is considered failed.
using Xunit;

public class MathTests
{
[Theory]
[InlineData(2, 3, 5)]
[InlineData(0, 0, 0)]
[InlineData(-1, 1, 0)]
public void Add_ValidInputs_ReturnsCorrectResult(int a, int b, int expected)
{
// Arrange
var calculator = new Calculator();

// Act
var result = calculator.Add(a, b);

// Assert
Assert.Equal(expected, result);
}
}

In summary, Fact is used for individual test cases, while Theory is used for parameterized tests where the same test logic is applied to multiple sets of inputs.

--

--