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?
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!;
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):
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.)

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