skip to content

xUnit

xUnit.net declares tests as facts and theories, builds a fresh class instance per test, and shares setup through fixtures. Interviewers probe its missing setup attribute and what v3 changed.

on this pageshow

explore

questions

15

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 does IClassFixture<T> share an expensive search index across one test class's tests, and when is it created and disposed?

level: middleimportance: must knowfreq 64%

basics

~20 s

Mark the test class with IClassFixture<SearchIndexFixture> and take SearchIndexFixture in its constructor. xUnit.net builds the fixture once, before the class's first test, passes that same instance to every test's fresh class instance, and disposes it after the class's last test.

open as a page

Why is an xunit.v3 test project built as an executable, and which packages and project settings does it need?

level: middleimportance: must knowfreq 55%

basics

~20 s

In xunit.v3 every test project is its own runnable program: the package generates an entry point and the build fails unless OutputType is Exe. Reference xunit.v3, which brings Microsoft.Testing.Platform v2, or xunit.v3.mtp-off when the project must run on VSTest only.

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.net, how do you write diagnostic output from a test with ITestOutputHelper, and why does Console.WriteLine not appear in the test result?

level: juniorimportance: should knowfreq 50%

basics

~20 s

Take ITestOutputHelper in the test class constructor and call WriteLine; the text is attached to that test's result. Console output is not attached because tests run in parallel and share one console, unless the xunit.v3 assembly opts in with [assembly: CaptureConsole].

open as a page

Which dotnet new template creates an xunit.v3 test project, and why does the .NET SDK's own xunit template not do so?

level: juniorimportance: should knowfreq 38%

basics

~10 s

The xunit3 template from the xunit.v3.templates package creates an xunit.v3 project. The SDK's built-in dotnet new xunit template still produces a v2 project with Microsoft.NET.Test.Sdk, xunit, xunit.runner.visualstudio and coverlet.collector.

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

In xunit.v3, why do tests in one class run one after another while different classes run in parallel, and how do you change that?

level: middleimportance: should knowfreq 52%

basics

~10 s

xUnit.net parallelises test collections, and by default each class is its own collection whose tests run serially. Regroup with [Collection] or [CollectionBehavior]; set mode and thread count with [assembly: Parallelization(...)] or xunit.runner.json.

open as a page

In xunit.v3, how does IAsyncLifetime let a fixture or test class build a search index asynchronously, and what changed from xUnit.net v2?

level: middleimportance: should knowfreq 48%

basics

~10 s

Implement IAsyncLifetime: xUnit.net awaits InitializeAsync right after constructing the fixture or test class, and awaits DisposeAsync at cleanup. In xunit.v3 InitializeAsync returns ValueTask and IAsyncLifetime extends IAsyncDisposable; in v2 both methods returned Task.

open as a page

In xunit.v3, how do Assert.Skip, SkipUnless/SkipWhen and Explicit = true differ from a fixed [Fact(Skip = "...")], and when do you use each?

level: middleimportance: should knowfreq 45%

basics

~20 s

A fixed Skip always skips. xunit.v3 adds run-time skips: Assert.Skip, SkipUnless and SkipWhen inside the test, or SkipUnless/SkipWhen naming a static bool property on the attribute. Explicit = true keeps a test out of normal runs until requested.

open as a page

In xunit.v3, what does TestContext.Current expose, and why should async tests pass TestContext.Current.CancellationToken to the code they call?

level: middleimportance: should knowfreq 42%

basics

~20 s

TestContext.Current is xunit.v3's ambient view of the running test: identity, state, output, attachments, warnings and a CancellationToken. Passing that token into async calls lets a timed-out or aborted test stop instead of running on in the background.

open as a page

Twelve xunit.v3 test classes each rebuild the same eight-second search index; how do you share one instance, and what does each option do to parallelism?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Put the classes in one test collection whose definition implements ICollectionFixture<SearchIndexFixture>: one index, but those classes run serially. Or register an assembly fixture: one index, classes stay parallel, so it must tolerate concurrent reads.

open as a page

You are migrating a ticketing library's xUnit.net v2 test suite to xunit.v3; what breaks, and in what order do you fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Swap the packages (xunit to xunit.v3, or xunit.v3.mtp-off to stay on VSTest), make the project an executable, fix compile errors from moved APIs, then run-time failures such as async void tests, and finally adopt v3 features.

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