Skip to content

Cratis Specifications: BDD tests with xUnit and NUnit

Last released · v5.3.0

Cratis Specifications adds a behavior-driven development (BDD) structure to .NET tests while keeping the xUnit or NUnit runner. The Cratis.Specifications namespace supplies the Given/When/Then lifecycle: Establish() sets up the context, Because() performs the action, and [Fact] or [Test] methods assert outcomes. Destroy() releases resources afterward.

For code-side specs outside .NET, Testing with Cratis shows TypeScript, Kotlin, and Java command and read-model specs in their own test frameworks, alongside C#. The Given/When/Then approach does not require this .NET library.

Use it when the test needs to explain a rule, not just detect a failure. For example, a developer investigating authentication should be able to find what happens for an admin user and which role the resulting token must contain. The class and folder names below make that behavior visible before the developer reads the setup.

Package Use it for
Cratis.Specifications Shared lifecycle discovery and helpers such as Catch.Exception.
Cratis.Specifications.XUnit xUnit Specification base class plus Should* assertion extensions over xUnit assertions.
Cratis.Specifications.NUnit NUnit Specification base class plus Should* assertion extensions over NUnit assertions.

Most Cratis repositories use central package versions. A runnable xUnit test project also needs the .NET test SDK, xUnit v2 and its Visual Studio runner; with central versions, reference them without version attributes:

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="Cratis.Specifications.XUnit" />
</ItemGroup>

For NUnit, use the test SDK, NUnit, NUnit3TestAdapter and Cratis.Specifications.NUnit instead. Outside a centrally versioned repository, pin compatible versions in the project or its central package file. From the test project directory, run dotnet test; a discovered successful run reports a nonzero count of passing tests.

Both packages use the Cratis.Specifications namespace.

The lifecycle methods are discovered by convention. They are optional, take no arguments, and can be void or Task.

Method BDD word Purpose
Establish() Given Build the context: inputs, services, mocks, existing state.
Because() When Perform the single behavior under specification.
[Fact] or [Test] Then Assert one fact about the result.
Destroy() Cleanup Release resources created by the spec.

The base class runs lifecycle methods across the inheritance chain, so reusable contexts can live in given/ classes and still participate in the same Establish() / Because() flow.

Start with the behavior. This example assumes your application supplies SecurityService, UserToken, Roles and UserMustBeSpecified; it is an excerpt of a spec for those domain types, not a standalone test project. A security service authenticates a user and returns a token with the user’s role and session id.

using Cratis.Specifications;
using Xunit;
namespace MyApp.Security.for_SecurityService;
public class when_authenticating_an_admin_user : Specification
{
SecurityService _subject = default!;
UserToken _result = default!;
void Establish() =>
_subject = new SecurityService();
void Because() =>
_result = _subject.Authenticate("admin", "correct-password");
[Fact] void should_indicate_the_users_role() =>
_result.Role.ShouldEqual(Roles.Admin);
[Fact] void should_have_a_session_id() =>
_result.SessionId.ShouldNotBeNull();
}

The class name, folder path, lifecycle methods, and facts form the sentence:

for_SecurityService / when_authenticating_an_admin_user / should_indicate_the_users_role.

Use Catch.Exception when the behavior is expected to fail. That keeps the exception as the observable result of Because().

using Cratis.Specifications;
using Xunit;
namespace MyApp.Security.for_SecurityService;
public class when_authenticating_without_a_user : Specification
{
SecurityService _subject = default!;
Exception _result = default!;
void Establish() =>
_subject = new SecurityService();
void Because() =>
_result = Catch.Exception(() => _subject.Authenticate(null!, null!));
[Fact] void should_require_a_user() =>
_result.ShouldBeOfExactType<UserMustBeSpecified>();
}

For async behavior, Catch.Exception(Func<Task>) returns a Task<Exception>; await it in an async Because() method:

async Task Because() =>
_result = await Catch.Exception(() => _subject.AuthenticateAsync(null!, null!));

This excerpt assumes AuthenticateAsync returns Task and the same _subject and _result fields as above.

When several specs share setup, move the setup into a given/ context and inherit from it.

for_SecurityService/
given/
no_user_authenticated.cs
when_authenticating_an_admin_user.cs
when_authenticating_without_a_user.cs
using Cratis.Specifications;
namespace MyApp.Security.for_SecurityService.given;
public class no_user_authenticated : Specification
{
protected SecurityService _subject = default!;
void Establish() =>
_subject = new SecurityService();
}
using Cratis.Specifications;
using Xunit;
namespace MyApp.Security.for_SecurityService;
public class when_authenticating_without_a_user : given.no_user_authenticated
{
Exception _result = default!;
void Because() =>
_result = Catch.Exception(() => _subject.Authenticate(null!, null!));
[Fact] void should_require_a_user() =>
_result.ShouldBeOfExactType<UserMustBeSpecified>();
}

Use reusable contexts for meaningful givens, not just to avoid a few repeated lines. The folder should still read like documentation.

NUnit uses the same Given/When/Then shape, with [Test] instead of [Fact]. The lifecycle also differs: NUnit facts can share fixture state, whereas the default xUnit lifecycle creates a fresh instance per fact.

using Cratis.Specifications;
using NUnit.Framework;
namespace MyApp.Security.for_SecurityService;
public class when_authenticating_an_admin_user : Specification
{
SecurityService _subject = default!;
UserToken _result = default!;
void Establish() =>
_subject = new SecurityService();
void Because() =>
_result = _subject.Authenticate("admin", "correct-password");
[Test] public void should_indicate_the_users_role() =>
_result.Role.ShouldEqual(Roles.Admin);
}
xUnit NUnit
Reference Cratis.Specifications.XUnit. Reference Cratis.Specifications.NUnit.
Facts use [Fact]. Facts use [Test].
The default xUnit lifecycle creates a new spec instance and calls Establish / Because per fact. NUnit’s setup and teardown run once for the fixture; facts can share its state.
Fact methods can be non-public in the Cratis style. NUnit test methods should be public.

The framework-specific packages expose assertion extension methods with the same names, so the spec reads the same whether it runs on xUnit or NUnit.

Assertion Use it for
ShouldEqual(expected) / ShouldNotEqual(expected) Value equality.
ShouldBeTrue() / ShouldBeFalse() Boolean facts.
ShouldBeNull() / ShouldNotBeNull() Null checks.
ShouldBeSame(expected) / ShouldNotBeSame(expected) Reference identity.
ShouldBeOfExactType<T>() Exact runtime type.
ShouldBeAssignableFrom<T>() Assignable runtime type.
ShouldContain(...) / ShouldNotContain(...) Strings, collections, and dictionaries.
ShouldBeEmpty() / ShouldNotBeEmpty() Collections.
ShouldContainSingleItem() Collections that should have exactly one item.
ShouldBeGreaterThan(...), ShouldBeLessThan(...), and range helpers Comparable values.

Use raw framework assertions only when there is no Should* helper for the fact you need.

Specs favor readable names over normal production-code naming conventions.

Level Pattern Example
Unit folder for_<TypeOrConcept> for_SecurityService
Shared context given/<context>.cs given/no_user_authenticated.cs
Behavior folder when_<action> when_authenticating
Condition file and_<condition>.cs or with_<state>.cs and_the_user_is_an_admin.cs
Simple behavior file when_<action>.cs when_authenticating_without_a_user.cs
Fact method should_<outcome> should_require_a_user

Choose a spec-project analyzer policy that explicitly supports readable BDD names; do not silence build warnings just to make a copied example pass.

Use Specifications for business rules and edge cases that future readers need to understand. A command’s validation, a domain service’s decision, or a projection’s response to an event can each be expressed as a context, one action and observable outcomes.

Use plain xUnit or NUnit tests when the test is pure infrastructure smoke, generated-code verification, or a very small assertion where the BDD structure would add noise.

For Cratis application tests, Specifications are usually the outer shape, while Arc and Chronicle provide the scenario objects inside it:

  • CommandScenario<TCommand> for Arc command behavior.
  • EventScenario for event append and constraint behavior.
  • ReadModelScenario<TReadModel> for projections and reducers.
  • ReactorScenario<TReactor> for event-driven side effects.

To test a command or read model in an application, continue with Testing with Cratis. It uses this lifecycle around Arc and Chronicle scenarios; you do not need a Screenplay model to start.