Skip to content

Nullable Reference Types (C# 8.0) and MSpec Tests #399

@alexringeri-xero

Description

@alexringeri-xero

I am encountering compilation errors when enabling the 'nullable reference types' language feature on an MSpec example. Is there a recommended approach for writing idiomatic MSpec tests with nullable reference types enabled?
https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references
https://devblogs.microsoft.com/dotnet/embracing-nullable-reference-types/

Example:

[Subject("Authentication")]
class When_authenticating_an_admin_user
{
    static SecurityService subject;
    static UserToken user_token;

    Establish context = () =>
        subject = new SecurityService(foo, bar);

    Because of = () =>
        user_token = subject.Authenticate("username", "password");

    It should_indicate_the_users_role = () =>
        user_token.Role.ShouldEqual(Roles.Admin);

    It should_have_a_unique_session_id = () =>
        user_token.SessionId.ShouldNotBeNull();
}

Error:

Non-nullable field 'subject' is uninitialized. Consider declaring the field as nullable.
One approach to resolve the issue is to declare subject and user_token as nullable, and assume they are not null after the Establish step. We can use the null-forgiving operator (!) to assume the reference is not null. This makes the tests harder to read and harder to determine the test intent.

I am looking for a better approach.

Updated Example:

[Subject("Authentication")]
class When_authenticating_an_admin_user
{
    static SecurityService? subject;
    static UserToken? user_token;

    Establish context = () =>
        subject = new SecurityService(foo, bar);

    Because of = () =>
        user_token = subject!.Authenticate("username", "password");

    It should_indicate_the_users_role = () =>
        user_token!.Role.ShouldEqual(Roles.Admin);

    It should_have_a_unique_session_id = () =>
        user_token!.SessionId.ShouldNotBeNull();
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions