Reputation: 370
Is possible to use
<Nullable>enable</Nullable>
in projects developed in nunit that uses fields that are initialized in OneTimeSetup without getting "warning CS8618: Non-nullable field '...' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.".
I expected to be an annotation like [NotNull] for fields that I initialize in OneTimeSetup, but didn't work.
Upvotes: 6
Views: 954
Reputation: 967
One (somewhat unpleasant!) way is to use the null forigiving operator:
private string _setInOneTimeSetUp = null!;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_setInOneTimeSetUp = "value used in tests";
}
This compiles with both <Nullable>enable</Nullable>
and <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
. Given NUnit will always call OneTimeSetUp
before anything else, it is logically safe, but any time you're using the null forgiving operator is a bit of a code smell.
Upvotes: 4