/dotnet-scenario-unittesting

A very easy way to write Unit Tests in xUnit, leveraging NSubstitute and AutoFixture.

Primary LanguageC#MIT LicenseMIT

.NET Scenario Unit Testing JoanComas.ScenarioUnitTesting

A very easy way to write Unit Tests in xUnit, leveraging NSubstitute and AutoFixture, complemented with FluentAssertions.

Installation

Install the JoanComas.ScenarioUnitTesting Nuget Package

Package Manager Console

Install-Package JoanComas.ScenarioUnitTesting

.NET Core CLI

dotnet add package JoanComas.ScenarioUnitTesting

Usage

  1. Decorate your test with [Theory, AutoData].
  2. Add a Scenario<MyClass> parameter to the test method.
  3. Use the Dependency<T> method to get a Mock, then configure it or assert it.
  4. Use the When() method to get the instance of the System Under Test.

Example:

[Theory, AutoData]
public void ExampleTest(Scenario<MyClass> scenario)
{
    scenario.Dependency<IMyInterface>().GetSomething(true).Returns(123);

    scenario.When().DoSomething();

    scenario.Dependency<IMyInterface>()
        .Received()
        .GetSomething(true);
}

Asp .NET Core Scenario Unit Testing JoanComas.ScenarioUnitTesting.AspNetCore

Based on the ScenarioUnitTesting, allows to instantiate a Controller (which won't be possilble with the Scenario class because of BindingInfo), just use the ControllerScenario instead.

Additionally, it has a ControllerContext property exposed to arrange it.

Finally, it makes sure that any DbContext uses an in-memory database, so that you don't have to arrange nor fake it to avoid a real database connection.

Installation

Install the JoanComas.ScenarioUnitTesting.AspNetCore Nuget Package

Package Manager Console

Install-Package JoanComas.ScenarioUnitTesting.AspNetCore

.NET Core CLI

dotnet add package JoanComas.ScenarioUnitTesting.AspNetCore

Usage

Example:

[Theory, AutoData]
public void ExampleTest(ControllerScenario<MyControllerClass> scenario)
{
    scenario.Dependency<IMyInterface>().GetSomething(true).Returns(123);
    scenario.ControllerContext().HttpContext.User.Identity?.Name.Returns("User1");

    scenario.When().DoSomething();

    scenario.Dependency<IMyInterface>()
        .Received()
        .GetSomething(true);
}

Important: If your Controller gets a DbContext injected, make sure that the types used in the DbSets have a primary key.

Contributing

  • Use a feature branch to produce changes.
  • Create a PR to merge back to main.

Releasing

The .NET and the ASP .Net Core libraries can be released independently.

In both cases, a tag with the specified version number and suffix has to be createad in git and pushed. This will trigger a workflow and create a PR autoamtically. Approving the PR will publish a new package in nuget.org.

.NET version

> git tag vX.Y.Z-net && git push origin vX.Y.Z-net

ASP .NET Core version

> git tag vX.Y.Z-aspnetcore && git push origin vX.Y.Z-aspnetcore