# NuGet, Testing and Analyzers — C#/.NET

Source: https://www.skillbyai.com/en/dotnet/p-tooling

> 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.

![A pipeline of three linked blocks: a package box, a gear with a magnifying glass, and a checklist with ticks.](assets/figures/dotnet/section-8-map.svg) — Figure 8.1 — The everyday .NET toolchain.

## An xUnit test

Arrange, act, assert; `[Theory]` runs the same test with several inputs.

```cs
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 test
```

## Make 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.

**Quiz:** Where can you set shared properties such as Nullable for every project in a repository?

- [ ] Program.cs
- [ ] appsettings.json
- [x] 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.
