Easy and fast extension of the famous Moq mocking framework for mocking and auto injection of classes when testing. Now with Blazor support.
$ dotnet add package FastMoq.WebEasy and fast extension of the Moq mocking framework for mocking and auto injection of classes when testing.
public class Mocker {} // Primary class for auto mock and injection. This can be used standalone from MockerTestBase using Mocks property on the base class.
public abstract class MockerTestBase<TComponent> where TComponent : class {} // Assists in the creation of objects and provides direct access to Mocker.
public abstract class MockerBlazorTestBase<T> : TestContext, IMockerBlazorTestHelpers<T> where T : ComponentBase // Assists in the creation of Blazor components and provides direct access to Mocker.public class CarTest : MockerTestBase<Car> {
[Fact]
public void TestCar() {
Component.Color.Should().Be(Color.Green);
Component.CarService.Should().NotBeNull();
}
}
public class Car {
public Color Color { get; set; } = Color.Green;
public ICarService CarService { get; }
public Car(ICarService carService) => CarService = carService;
}
public interface ICarService
{
Color Color { get; set; }
ICarService CarService { get; }
bool StartCar();
}public class CarTest : MockerTestBase<Car> {
public CarTest() : base(mocks => {
mocks.Initialize<ICarService>(mock => mock.Setup(x => x.StartCar).Returns(true));
}
}Auto injection allows creation of components with parameterized interfaces. If an override for creating the component is not specified, the component will be created will the default Mock Objects.
Additionally, the creation can be overwritten and provided with instances of the parameters. CreateInstance will automatically match the correct constructor to the parameters given to CreateInstance.
Mocks.CreateInstance(new MockFileSystem()); // CreateInstance matches the parameters and types with the Component constructor.When multiple classes derive from the same interface, the Interface Type Map can map with class to use for the given injected interface. The map can also enable mock substitution.
public class TestClassDouble1 : ITestClassDouble {}
public class TestClassDouble2 : ITestClassDouble {}This code maps ITestClassDouble to TestClassDouble1 when testing a component with ITestClassDouble.
Mocker.AddType<ITestClassDouble, TestClassDouble1>();The map also accepts parameters to tell it how to create the instance.
Mocks.AddType<ITestClassDouble, TestClassDouble1>(() => new TestClassDouble());