Precept 0.14.0

Test data

Almost every suite needs records to exist before a scenario can start: a user to sign in as, a client to place an order for, a vehicle to book in. Precept.TestData is where those live, so they stop being string literals scattered through step definitions.

public void ConfigureServices(IServiceCollection services, PreceptSettings settings) =>
    services.AddPreceptTestData();
// testdata.json, beside the test binary
{
  "users": {
    "admin": { "username": "admin@acme.test", "password": "{{env:ADMIN_PASSWORD}}" }
  },
  "clients": {
    "new": { "name": "Acme {{unique}}", "email": "acme-{{unique}}@acme.test" }
  }
}
var admin = TestData.Get<TestUser>("admin");        // users:admin
var van = TestData.Get<Vehicle>("vehicles:van");    // or by full path
var password = TestData.Value("users:admin:password");

The set a type reads from is the plural of the type name, with a Test prefix and a Data/Dto/Model suffix dropped: TestUser reads users, Vehicle reads vehicles, Company reads companies. To name it yourself, put [TestDataSet("people")] on the type, or call data.Map<Person>("users") at registration. Lookups are case-insensitive.

The module's types live in the Precept namespace, so a step definition that already uses Precept needs no further using.

Data files must reach the output directory:

<ItemGroup>
  <None Update="testdata*.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

Environment-specific data#

testdata.json is overlaid by testdata.{environment}.json and then by PRECEPT_TESTDATA__* environment variables. That is the same order Precept uses for settings, against the same environment; see Environments. An overlay only has to carry what differs:

// testdata.staging.json
{ "users": { "admin": { "username": "admin@staging.acme" } } }

The password should not be in either file. That is what the environment variables are for:

PRECEPT_TESTDATA__USERS__ADMIN__PASSWORD='...'

That sets users:admin:password without it ever being written down in the repository. __ becomes the : separator, exactly as PRECEPT_WEB__BASEURL works for settings.

To load more files, for example one per domain area, call data.AddJsonFile("vehicles.json"). Each file brings its own vehicles.{environment}.json overlay. TestData:Files and TestData:Directory in precept.json do the same from configuration, and TestData:LeaseTimeoutMilliseconds lives there too.

Dynamic values#

Any value in a data file may carry {{token}} placeholders. They are expanded when the value is read, not when the file is loaded. A suite that inserts the same email address on every run fails on the second run; tokens are the answer to that.

Token Gives
{{unique}} A short id, the same everywhere in one scenario and different in the next.
{{unique:buyer}} A second, independent one, for when a scenario needs two.
{{run}} A short id that is the same for the whole run, so everything one run created can be found, and deleted, together.
{{guid}}, {{guid:N}} A GUID, optionally in a .NET format.
{{now}}, {{now:yyyy-MM-dd}}, {{now:+2d:HH:mm}}, {{today}}, {{yesterday}}, {{tomorrow}} A UTC timestamp, optionally shifted by s, m, h, d, w, M (months) or y, and formatted. Months and years go through the calendar, so {{today:-18y}} is the same date eighteen years ago, leap days or not.
{{date:-80y:-18y}}, {{date:2024-01-01:2024-12-31:dd/MM/yyyy}} A date between two bounds, each an offset or a yyyy-MM-dd date, formatted like {{today}} unless a format follows.
{{random}}, {{random:1000-9999}} A whole number, optionally in an inclusive range.
{{decimal:1.00-99.99}} A decimal in an inclusive range, with as many places as the bounds were written with.
{{bool}} true or false.
{{pick:red\|green\|blue}} One of the listed values.
{{digits:6}}, {{letters:8}}, {{alphanumeric:10}}, {{hex:16}} Random text of that length, eight by default. Add :upper for upper case, as in {{alphanumeric:5:upper}}.
{{env:BUILD_ID}}, {{env:BUILD_ID\|local}} An environment variable, with an optional fallback.
{{setting:Api:BaseUrl}} A value from precept.json.
{{ref:users:admin:username}} Another test data value, so two records agree.

Add your own tokens for whatever the domain needs, such as a VIN with a valid check digit, a national insurance number, or an IBAN:

services.AddPreceptTestData(data => data.AddToken("vin", c => Vin.Generate(c.Argument)));

The context a token receives carries its argument, the store, and the scope its value is memoised in. c.Scope is the running test's scope, which is how {{unique}} stays the same for a scenario. c.Store.RunScope is the whole run's, for a value every test should share, such as the batch a nightly run files everything under:

data.AddToken("batch", c => c.Store.RunScope.Value("batch", () => $"NIGHTLY-{DateTime.UtcNow:yyyyMMdd-HHmm}"));

A literal {{ is written \{{, for a value that is itself a template for the system under test. In a JSON file that is "\\{{name}}", since JSON escapes the backslash too.

Which values hold still#

Only {{unique}} and {{run}} are stable on their own. Every other generator produces a fresh value each time it is expanded. A scenario that says "Autotest_{{alphanumeric:5}}" in a When and again in a Then is talking about two different names. {{unique}} is the token for that job: it is the same value everywhere in one scenario and a different one in the next, and its eight clock-seeded characters collide far later than five random ones.

When a field cannot take those eight characters, or must be digits, add #name after any token. The value it produced is remembered under that name for the rest of the scope:

{ "orders": { "new": { "code": "{{digits:6#code}}", "reference": "ORD-{{digits:6#code}}" } } }

Both fields carry the same six digits, and a step that resolves "{{digits:6#code}}" gets them too.

Stability is what makes generated values usable. Within one scenario, Get<Client>("new") returns the same client every time, so the {{unique}} in the name and the one in the email agree, and every step sees what the first one created. New<Client>("new") deliberately breaks that: it reads another one, with its own generated values, which is how a scenario gets two different customers.

A retry generates fresh values, because a test that failed on a duplicate key needs its rerun to stop colliding with what it already inserted. {{run}} is the one exception. It is the same across every test and every retry, which is what makes it useful as the prefix a nightly clean-up job searches for.

Data the tests have to create#

Reading a template only goes so far. Most data has to exist in the system under test. A factory says how to put it there and how to take it away:

services.AddPreceptTestData(data => data.Factory<Client>(
    create: async (_, client) =>
    {
        var created = await Rest.Post("/clients").WithJsonBody(client).SendAsync();
        await Assert.That(created).ToHaveStatusAsync(HttpStatusCode.Created);
        return created.Json<Client>();
    },
    delete: async (_, client) => await Rest.Delete($"/clients/{client.Id}").SendAsync()));
var client = await TestData.CreateAsync<Client>("new");

The template comes from clients:new. The factory creates it through whatever the suite already uses: an API call, a database insert, a gRPC request. The delete runs when the test ends, after the [AfterTest] hook, whatever the verdict was.

Call Lifetime
CreateAsync<T>(key) One per call, removed when the test ends.
GetOrCreateAsync<T>(key) One per test, however many steps ask for it.
SharedAsync<T>(key) One per run, removed when the run ends. Treat it as read-only, because parallel tests share it.

Pooled data#

Some data cannot be generated and cannot be shared: three pre-provisioned accounts on a partner system, a handful of licensed test vehicles. Declare that set as a pool, and a scenario takes one item for itself:

{ "drivers": [ { "username": "driver-one" }, { "username": "driver-two" } ] }
var driver = await TestData.LeaseAsync<TestUser>("drivers");
await signIn.SignInAsync(driver.Value.Username, driver.Value.Password);

Nothing else in the run holds that item until the lease is released, which happens when the test ends. A scenario that throws does not take an account down with it. Dispose the lease to give the item back sooner.

When every item is in use, the next test waits. After TestData:LeaseTimeoutMilliseconds it gives up with an inconclusive verdict rather than a failure, because running out of accounts is an environment problem, not a defect in the code under test.

From Gherkin#

Steps refer to data by name, so the feature file says what the scenario means rather than what the credentials are:

Given I am signed in as the "admin" user
When I create a client
Then the client should appear on the dashboard
[Binding]
public class ClientSteps(SignInPage signIn)
{
    [Given("I am signed in as the {string} user")]
    public Task SignIn(string key)
    {
        var user = TestData.Get<TestUser>(key);
        return signIn.SignInAsync(user.Username, user.Password);
    }

    [When("I create a client")]
    public Task CreateClient() => TestData.GetOrCreateAsync<Client>("new");
}

Some values belong in the scenario rather than in a data file, such as the name of the brand a scenario creates. Those may carry tokens too. TestData.Resolve expands them in a string that came from the feature file:

[When("I create the brand {string}")]
public Task CreateBrand(string name) => _api.CreateBrandAsync(TestData.Resolve(name));
// Scenario: When I create the brand "Autotest_{{unique}}"

A When and a Then that both resolve "Autotest_{{unique}}" name the same brand, because {{unique}} is stable for the scenario.

The step does the resolving, on purpose. A step argument reaches its definition exactly as the feature file wrote it. An int, a DateTime or a table bound to objects goes through Reqnroll's own conversion untouched, and a system under test with a {{ syntax of its own is never surprised.

When the expanded value is a number or a date rather than text, Resolve<T> reads it as one. Value<T> does the same for a path in a data file:

[When("I register a driver born on {string}")]
public Task Register(string birthDate) => _api.RegisterAsync(TestData.Resolve<DateOnly>(birthDate));
// Scenario: When I register a driver born on "{{today:-18y}}"

var quantity = TestData.Value<int>("orders:new:quantity");

The conversion is culture-invariant, so {{decimal:1.00-99.99}} reads as a decimal on a machine that writes a comma as well as on one that writes a point. Anything with a text form works: numbers, bool, Guid, DateTime, DateOnly, TimeSpan, enums.

Precept 0.14.0 · MIT · © 2026

Esc