Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable reference types and MSTest ClassInitialize

MSTest offers a [ClassInitialize] attribute, which can be placed on a static method to provide one-time initialization.

Assume I have a static member in a test class that I wish to initialize in such [ClassInitialize] method. How can I mark that it's not nullable?

For example, consider the following code:

private static Database _database;

[ClassInitialize]
public static void InitializeClass(TestContext testContext)
{
    _database = new Database();
}

With #nullable enable, I get a very understandable warning: CS8618 Non-nullable field '_database' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.

I could move the initialization to the constructor (but it would happen for each test method). I could use the null-forgiving operator (!). Are there better options to mark that _database is not null?

like image 893
Tomer Avatar asked Mar 16 '26 20:03

Tomer


2 Answers

I prefer to use null forgiving in situations like this. Specifically, you can just set properties you know will be populated, but the compiler can't pick up using null!.

For example:

private static Database _database = null!;
like image 196
Dylan Smith Avatar answered Mar 18 '26 10:03

Dylan Smith


I really don't like the = null!; syntax, and I can't really pinpoint why. It seems ugly and really unnecessary. I don't want to update hundreds of tests.

Anyway, I did this (in Visual Studio):

  1. Right click the Test project > Properties
  2. At the top, search properties for "suppress".
  3. Add CS8618 to the list separated by a semi-colon.
  4. Hit Save.

I only plan to do this in test projects. I sometimes have async code I need to use in my test setup, so I cannot initialize these members in a constructor. (Constructors cannot be async.)

enter image description here

like image 31
Jess Avatar answered Mar 18 '26 10:03

Jess



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!