In this lesson, you will learn how to treat nullable reference type (NRT) warnings as critical test failures to ensure your production code adheres to strict safety contracts.
The Problem: Silently Ignoring Nullability
When you enable <Nullable>enable</Nullable> in your project, the compiler flags potential NullReferenceException risks. However, in large test suites, developers often ignore these warnings or rely on ! (the null-forgiving operator) to silence the compiler. If your tests aren’t verifying nullability, you might be shipping code that masks runtime nulls behind sloppy test setups.
Enforcing Strict Safety in Tests
To ensure your test project is as robust as your production code, you should configure your test projects to treat all nullable warnings as errors. This forces you to handle nulls explicitly in your mocks and assertions rather than "cheating" with the null-forgiving operator.
Add this to your test project’s .csproj file:
<PropertyGroup>
<Nullable>enable</Nullable>
<WarningsAsErrors>nullable</WarningsAsErrors>
</PropertyGroup>
Once this is set, a test that passes a null into a non-nullable parameter—or fails to check a result that could be null—will cause the build to fail immediately.
Testing for Nullability Intent
When writing tests, use Assert.NotNull (or your preferred assertion library's equivalent) before accessing a member. This serves two purposes:
- It validates your business logic’s runtime behavior.
- It satisfies the static analysis compiler, allowing you to avoid the
!operator entirely.
[Fact]
public void GetUser_ReturnsValidUser()
{
var service = new UserService();
var result = service.GetUser(1);
// Explicit assertion proves the contract is met
// and satisfies the compiler's null-checking engine.
Assert.NotNull(result);
Assert.Equal("Alice", result.Name);
}
By enforcing WarningsAsErrors, you treat your test code with the same rigor as your application code. You stop "guessing" if a value will be present and start enforcing the safety contracts that NRTs are designed to provide.
Key Takeaway: By setting WarningsAsErrors to nullable in your test projects, you force your test suite to become an active participant in your null-safety strategy rather than a source of hidden technical debt.