Skip to content

Testing with TUnit

Haitch.Unions.TUnit.Assertions provides assertions for Result<T> and Optional<T>, including their Task<...> forms.

Terminal window
dotnet add package Haitch.Unions.TUnit.Assertions
await result.AssertOk();
await result.AssertOk(expectedValue);
await result.AssertError();
await result.AssertError(expectedError);

Each of the six error kinds has a helper that asserts the result is Error and returns the typed error for further assertions:

ValidationError error = await result.AssertValidation();
await Assert.That(error.Failures).ContainsKey("email");
HelperReturns
AssertNotFound()NotFoundError
AssertValidation()ValidationError
AssertConflict()ConflictError
AssertUnauthorized()UnauthorizedError
AssertForbidden()ForbiddenError
AssertUnexpected()UnexpectedError

For a custom error kind, or any kind without a dedicated helper, use the general AssertError<TError>(). It’s declared alongside T in the same extension block as the Result<T> it applies to, so both type arguments are given explicitly at the call site:

var error = await result.AssertError<int, ValidationError>();
await optional.AssertSome();
await optional.AssertSome(expectedValue);
await optional.AssertNone();

Every assertion above also works directly on Task<Result<T>> and Task<Optional<T>>, awaiting the task first:

await GetUserAsync(id).AssertOk();
var error = await GetUserAsync(id).AssertNotFound();