liveBook · Manning

Attribute

As explained in F# in Action: A Revised Edition of Get Programming with F#

An attribute is metadata attached to a program element to provide declarative information consumed by the compiler or runtime.

An attribute adds a declaration that a tool can recognize. In F# tests, `[<Fact>]` marks a function for XUnit’s test runner to discover. This avoids manually gathering tests into a list, as you would with Expecto. section 14.4

[<Fact>]
let ``My guitar gently weeps`` () =
    let input = Guitar
    let output = play input
    Assert.Equal("Wah wah", output)
 
[<Fact>]
let ``Drums go bang`` () =
    let input = Drums
    let output = play input
    Assert.Equal ("Ba dumm tss", output)

Each `[<Fact>]` sits immediately above a test function. The functions call `play` and check its output with `Assert.Equal`. section 14.4

Attributes can also identify shared test setup: `[<TestSetup>]` marks a setup function. Use the attribute expected by your test framework; discovery and execution then depend on that framework’s runner. An XUnit class-library project can be created with `dotnet new xunit -lang F#` and run with `dotnet test`. section 14.4

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Shows attribute placement and its effect on test discovery, without explaining compiler or runtime internals.
Examples
Shows two `[<Fact>]` functions that test instrument sounds with `Assert.Equal`.
What it assumes
Assumes basic F# functions and test assertions; demonstrates attribute syntax in a concrete test.
What you can do after
Apply it via XUnit to mark F# tests for discovery and run them with `dotnet test`.
How it connects
Connects attributes to XUnit, NUnit, test runners, test discovery, test setup, and Expecto.

Also explained in

Compare how 28 books explain attribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.