I have an Asp.net Core 6 Web Api project.
I am trying to protect against NullReferenceException.
I have added the following setting to all projects:
<Nullable>enable</Nullable>
I have fixed the code base, but I get warnings in Unit and integration tests:
**viewModel**.Message.Should().Be("Aaaa");
viewModel is underlined for a possible null reference.
I think enabling this feature for unit tests is useless. When you write the unit test, you set up the conditions - so you know if something is null.
Instead of putting the "!" (damnit) operator everywhere to tell the compiler I am sure it is not null, I believe I should just remove the enable setting from test projects.
Does anyone see a valid reason enable should stay in Unit test projects?
CodePudding user response:
I would <Nullable>disable</Nullable>
the unit test project.
My preference would be for a unit test to fail if anything is null, otherwise I might miss out on a codepath that is not working as expected. I see a unit test as something that should send alarm bells ringing at any conceivable moment, as I would rather a unit test fail in front of me in preference to a production error that I have to bugfix later on.
CodePudding user response:
Assuming your unit test project is separate from the project where the code is being tested, the setting should at least match the configuration of the project being tested.
If the nullable reference types are enabled in the project being tested then there is no harm in enabling it for the unit tests.
However nullable reference types are disabled in the project being tested and enabled in the unit tests project, this might lead to a scenario where a unit test passes but there is a bug (e.g. null reference exception) in the code the unit test is testing.
You never want unit tests to pass when there is a problem in the code since the whole point of them is to alert you to issues in the code.
The most safe option is to disable nullable reference types in the unit test project regardless of the setting in the project being tested. This way you are protected if the setting is changed.