A very easy way to write Unit Tests in xUnit, leveraging NSubstitute and AutoFixture, complemented with FluentAssertions.
Install the JoanComas.ScenarioUnitTesting Nuget Package
Install-Package JoanComas.ScenarioUnitTesting
dotnet add package JoanComas.ScenarioUnitTesting
- Decorate your test with
[Theory, AutoData]
. - Add a
Scenario<MyClass>
parameter to the test method. - Use the
Dependency<T>
method to get a Mock, then configure it or assert it. - 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);
}
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.
Install the JoanComas.ScenarioUnitTesting.AspNetCore Nuget Package
Install-Package JoanComas.ScenarioUnitTesting.AspNetCore
dotnet add package JoanComas.ScenarioUnitTesting.AspNetCore
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.
- Use a feature branch to produce changes.
- Create a PR to merge back to main.
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.
> git tag vX.Y.Z-net && git push origin vX.Y.Z-net
> git tag vX.Y.Z-aspnetcore && git push origin vX.Y.Z-aspnetcore