dotnet-scenario-unittesting
A very easy way to write Unit Tests in xUnit, leveraging NSubstitute and AutoFixture.
I recommend to complement it with FluentAssertions.
How to Use
- Decorate your test with
[Theory, AutoData]
. - Add a
Scenario<MyClass>
parameter to the test method. - Use the
When()
method to get the instance of the System Under Test. - Use the
Dependency<T>
method to get a Mock, then configure it or assert it.
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
Use the ControllerScenario
instead.
This allows to instantiate a Controller (which won't be possilble with the Scenario
class because of BindingInfo).
Additionally, it has a ControllerContext
property exposed to arrange it.
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);
}