Lesson 22 / 25
NuGet, Testing and Analyzers
Manage packages, write unit tests and let analyzers enforce quality.
The everyday toolchain
NuGet is .NET's package manager: dotnet add package Serilog adds a <PackageReference> to the project file, and dotnet restore downloads packages. For multi-project solutions, Central Package Management (Directory.Packages.props) keeps versions in one place, and Directory.Build.props shares settings like Nullable and TreatWarningsAsErrors. Common test frameworks are xUnit, NUnit and MSTest; run them with dotnet test. Mocking libraries such as NSubstitute or Moq replace dependencies, and assertion libraries make failures readable. Roslyn analyzers run during build: the built-in .NET analyzers catch bugs and performance issues, configured through .editorconfig and <AnalysisLevel>; dotnet format applies code style. Use dotnet list package --vulnerable and --outdated to keep dependencies safe and current.
Build, test, analyse
Restore packages, compile with analyzers, then run tests, locally and in CI alike.
An xUnit test
Arrange, act, assert; [Theory] runs the same test with several inputs.
using Xunit;
public class BankAccountTests
{
[Fact]
public void Withdraw_more_than_balance_fails_and_keeps_balance()
{
var acct = new BankAccount("Asha") { Ifsc = "SBIN0001234" };
acct.Deposit(100m);
bool ok = acct.TryWithdraw(150m);
Assert.False(ok);
Assert.Equal(100m, acct.Balance);
}
[Theory]
[InlineData(0)]
[InlineData(-5)]
public void Deposit_rejects_non_positive_amounts(int amount)
{
var acct = new BankAccount("Asha") { Ifsc = "SBIN0001234" };
Assert.Throws<ArgumentOutOfRangeException>(() => acct.Deposit(amount));
}
}
// dotnet new xunit -n Bank.Tests && dotnet add Bank.Tests reference Bank
// dotnet testMake warnings fail the build
Warnings that never fail the build accumulate until nobody reads them. Turn on TreatWarningsAsErrors in new projects, and suppress specific rules in .editorconfig with a reason when you must.
Quick check: Where can you set shared properties such as Nullable for every project in a repository?
- Program.cs
- appsettings.json
- Directory.Build.props
- global usings
Answer
Directory.Build.props — Directory.Build.props is imported by all projects below it, so shared MSBuild settings live there.