skip to content

Facts & Theories

[Fact] and [Theory] with [InlineData], [MemberData] and TheoryData<T> declare xUnit tests, each on a new class instance. Interviewers ask why a constructor replaces setup attributes.

on this pageshow

explore

questions

5

In xUnit.net, what is the difference between [Fact] and [Theory], and how does [InlineData] supply a theory's test cases?

level: juniorimportance: must knowfreq 80%

answer

  1. invariant versus data-driven claim
  2. [Fact] methods take no parameters
  3. one [InlineData] attribute per row
  4. attribute arguments must be constants
  5. Skip = "reason" and [Trait(name, value)]

basics

~20 s

[Fact] marks a parameterless test that must always pass; [Theory] marks a parameterised test that must hold for every data row. Each [InlineData(...)] supplies one row of constant arguments, and xUnit.net runs and reports the method once per row.

solid answer

~50 s

In xUnit.net a `[Fact]` is a test with no inputs: it states something that is always true, such as "zero income owes zero tax". A `[Theory]` states a rule that must hold for a family of inputs, so the method takes parameters and needs at least one data attribute. `[InlineData]` is the simplest source: one attribute per row, values matched to parameters by position, and each row reported as its own pass or fail. Because they are attribute arguments, the values must be compile-time constants. Mistakes become failing tests rather than silent passes: a `[Fact]` with parameters reports "[Fact] methods are not allowed to have parameters. Did you mean to use [Theory]?", and a theory with no rows fails with "No data found". Both attributes take `Skip = "reason"` and `DisplayName`, and `[Trait("Category", "Tax")]` tags tests with metadata that runners can filter on.

code

csharp · 18 lines
csharp
public class TaxCalculatorTests
{
    private readonly TaxCalculator _calculator = new(TaxBrackets.Default2026);

    [Fact]
    public void Zero_income_owes_no_tax() =>
        Assert.Equal(0m, _calculator.Calculate(0m));

    [Theory]
    [InlineData(10_000, 0)]
    [InlineData(25_000, 3_000)]
    [InlineData(40_000, 6_000)]
    [InlineData(50_000, 10_000)]
    [InlineData(250_000, 90_000, Skip = "2027 top rate not confirmed")]
    [Trait("Category", "Brackets")]
    public void Tax_follows_the_bracket_table(int income, int expectedTax) =>
        Assert.Equal<decimal>(expectedTax, _calculator.Calculate(income));
}

go deeper

for a junior

Recall the split: [Fact] for a parameterless invariant, [Theory] plus [InlineData] rows for a rule over many inputs, one reported result per row.

for a middle

Explain positional binding, the constant-only limit of attribute arguments, and the error entries xUnit.net produces for a parameterised fact or a theory without data.

for a senior

Show judgement about granularity: when a case deserves its own named fact, when rows belong in one theory, and how per-row Skip and traits keep a large table manageable.

for a principal

Frame data-driven tests as a maintenance trade-off: one rule with visible examples beats copy-pasted facts, but only if every row stays individually readable in reports.

## Facts and theories: two kinds of claim xUnit.net names its two test attributes after logic. A **fact** is an invariant: a statement that is true with no inputs at all, such as "an income of zero owes zero tax". A **theory** is a rule that should be true for every member of a set of inputs, such as "tax follows the bracket table". The data rows you attach to a theory are examples chosen to try to disprove it; if any row fails, the rule is broken for that input. In code the difference is structural. A `[Fact]` method has no parameters. A `[Theory]` method declares parameters and gets its arguments from one or more **data attributes**: `[InlineData]`, `[MemberData]` or `[ClassData]`. | | `[Fact]` | `[Theory]` | |---|---|---| | Parameters | none allowed | one per value in a row | | Data source | none | `[InlineData]`, `[MemberData]`, `[ClassData]` | | Results | one | one per data row | | Typical use | a single named behaviour or edge case | the same rule over many inputs | ## How [InlineData] maps rows to parameters `InlineDataAttribute` takes `params object?[]? data` and allows multiple uses on one method, so each attribute is one row: - **Positional binding**: the first value goes to the first parameter, the second to the second, and so on. - **Constants only**: the C# compiler accepts only constant attribute arguments, so numbers, strings, `bool`, `char`, enum values, `typeof(...)`, `null` and one-dimensional arrays work. A `decimal` literal, a `DateTime` or an object instance cannot be written there, which is why such data moves to other data attributes. - **A lone null**: `[InlineData(null)]` is treated as one `null` argument, not as "no data". - **Optional and params parameters**: xUnit.net fills declared default values and packs surplus values into a trailing `params` array. - **Per-row options**: `InlineData` inherits `Skip`, `TestDisplayName`, `Timeout` and `Traits` from `DataAttribute`, so one row can be skipped or renamed without touching the others. ## What goes wrong, and how xUnit.net reports it xUnit.net reports declaration mistakes as failing entries instead of quietly ignoring the method: 1. A `[Fact]` with any parameter, even an optional one, becomes an error: "[Fact] methods are not allowed to have parameters. Did you mean to use [Theory]?" 2. A generic `[Fact]` method is rejected with "[Fact] methods are not allowed to be generic." 3. A `[Theory]` whose data produces no rows fails with "No data found for Class.Method". Setting `SkipTestWithoutData = true` on the theory reports it as skipped instead. 4. A row with fewer values than required parameters fails when it runs: "The test method expected 2 parameter values, but 1 parameter value was provided." ## Skipping, naming and tagging - `[Fact(Skip = "Waiting for the 2027 bracket table")]` reports the test as skipped with that reason; the method is not run. On a `[Theory]`, an unconditional `Skip` produces a single skipped entry rather than one per row. - `DisplayName` replaces the method name in reports; theory rows still append their argument values. - `[Trait("Category", "Brackets")]` attaches a name/value pair to a method, a class or the whole assembly, and may be applied several times. A trait is **metadata only**: it changes nothing about how the test runs, and a runner or command-line filter decides what to include or exclude by it. ## The tax-bracket example The calculator under test charges 0% up to 10,000, 20% from 10,000 to 40,000 and 40% above that. One fact pins the zero case; one theory walks the table: ```csharp [Fact] public void Zero_income_owes_no_tax() => Assert.Equal(0m, _calculator.Calculate(0m)); [Theory] [InlineData(25_000, 3_000)] [InlineData(50_000, 10_000)] public void Tax_follows_the_brackets(int income, int expectedTax) => Assert.Equal<decimal>(expectedTax, _calculator.Calculate(income)); ``` The values are whole numbers so they can stay `int` constants inside the attributes; amounts with cents need a data source that can hold `decimal` values. In the test report the theory appears once per row with its arguments in the name, ending in `(income: 50000, expectedTax: 10000)`, so a failure tells you which bracket broke. That is the practical reason to prefer one theory over a series of near-identical facts: the rule is written once, and every example is still a visible, separately reported result. ## The assertions you pair with them - `Assert.Equal(expected, actual)` takes the expected value **first**; swapping them still passes or fails correctly but prints a misleading failure message. - `Assert.Collection(lines, first => ..., second => ...)` checks a sequence element by element with one inspector per element, and fails if the counts differ, which suits a per-bracket breakdown of the tax. - `Assert.Throws<T>` covers the error paths, such as negative income. Keep a separate `[Fact]` when one case deserves its own name in the report, such as the zero-income case above or a rule that exists only for one input.

  • How do you skip one [InlineData] row rather than the whole theory?
    Set `Skip` on that data attribute: `[InlineData(250_000, 90_000, Skip = "2027 top rate not confirmed")]`. `InlineData` inherits `Skip` from `DataAttribute`, so only that row is reported as skipped while the other rows still run. Putting an unconditional `Skip` on `[Theory]` instead skips the whole method as one skipped entry.
  • What happens when an [InlineData] row has fewer values than the theory has parameters?
    The row still becomes a test, but it fails when it runs with a message such as "The test method expected 2 parameter values, but 1 parameter value was provided." Optional parameters with default values and a trailing `params` array are the exceptions: xUnit.net fills the defaults and packs extra values into the array before calling the method.

  • A [Fact] may take parameters as long as each one has a default value.
  • A [Theory] with no data attributes simply runs once with default argument values.
  • xUnit.net tests are marked with [Test] or [TestMethod] like the other .NET frameworks.
  • [InlineData(10_000.50m, 2_100.10m)] compiles because decimal is a built-in numeric type.
  • Adding [Trait] to a test excludes it from normal runs until that trait is requested.
open as a page

In xUnit.net, why do you put per-test setup in the test class constructor and teardown in Dispose instead of attributes?

level: middleimportance: must knowfreq 66%

basics

~20 s

xUnit.net creates a new instance of the test class for every test, including each theory row, so the constructor is per-test setup and Dispose or DisposeAsync is per-test teardown. Instance fields start fresh for every test without any attributes.

open as a page

In xUnit.net, how do you assert that code throws, and how do Assert.Throws, Assert.ThrowsAny and Assert.ThrowsAsync differ?

level: juniorimportance: should knowfreq 60%

basics

~10 s

Wrap the call in a lambda: Assert.Throws<T> passes only for exactly T, Assert.ThrowsAny<T> also accepts derived exceptions, and Assert.ThrowsAsync<T> handles Task-returning code and must be awaited. Each returns the caught exception for further asserts.

open as a page

In xunit.v3, when do you move a theory from [InlineData] to [MemberData] or [ClassData], and what does TheoryData<T> add?

level: middleimportance: should knowfreq 52%

basics

~20 s

Move off [InlineData] when values cannot be attribute constants (decimal, DateTime, objects), are computed, or are shared. [MemberData] reads a public static member, [ClassData] instantiates a reusable data class, and TheoryData<T1, T2> makes the compiler check every row.

open as a page

With xunit.v3, why does a theory fed TaxReturn objects through [MemberData] show up as one test case instead of one per row, and how do you fix it?

level: seniorimportance: nice to knowfreq 26%

basics

~20 s

xunit.v3 lists a test case per theory row only when discovery pre-enumerates the data and can serialize every argument. A plain TaxReturn class is not serializable, so the theory collapses to one case. Pass serializable values, or implement IXunitSerializable.

open as a page