FastMoq
Search Results for

    Show / Hide Table of Contents

    Class MockerTestBase<TComponent>

    Mock Test Base with Automatic Mocking using Mocker. This class contains the Mocks property to create and track all Mocks from creation of the component.

    Inheritance
    object
    MockerTestBase<TComponent>
    Implements
    IDisposable
    Inherited Members
    object.Equals(object)
    object.Equals(object, object)
    object.GetHashCode()
    object.GetType()
    object.MemberwiseClone()
    object.ReferenceEquals(object, object)
    object.ToString()
    Namespace: FastMoq
    Assembly: FastMoq.Core.dll
    Syntax
    public abstract class MockerTestBase<TComponent> : IDisposable where TComponent : class
    Type Parameters
    Name Description
    TComponent

    The type of the t component.

    Examples

    Use MockerTestBase<TComponent> when you want the component under test created automatically with constructor dependencies resolved from FastMoq's provider-first pipeline.

    The base class auto-resolves constructor dependencies, so you do not need to call GetOrCreateMock just to make a dependency exist before verification. When you do need the tracked mock handle itself, use GetOrCreateMock<T>(MockRequestOptions?) in a custom create path.

    public sealed class OrderSubmitterTests : MockerTestBase<OrderSubmitter>
    {
        [Fact]
        public void Submit_should_publish_the_order_id()
        {
            Component.Submit(42);
    
        Component.LastSubmittedOrderId.Should().Be(42);
        Mocks.Verify<IOrderGateway>(x => x.Publish(42), TimesSpec.Once);
    }
    

    }

    The base class creates OrderSubmitter before the test body runs, so the test can assert directly against Component.

    public interface IOrderGateway
    {
        void Publish(int orderId);
    }
    

    public sealed class OrderSubmitter { private readonly IOrderGateway _gateway;

    public OrderSubmitter(IOrderGateway gateway) => _gateway = gateway;
    
    public int? LastSubmittedOrderId { get; private set; }
    public string SubmissionChannel { get; set; } = "default";
    
    public void Submit(int orderId)
    {
        LastSubmittedOrderId = orderId;
        _gateway.Publish(orderId);
    }
    

    }

    Use CreatedComponentAction when you need a final arrangement step after construction, such as setting mutable state that is part of the test context.

    protected override Action<OrderSubmitter> CreatedComponentAction => component =>
        component.SubmissionChannel = "priority";

    Constructors

    MockerTestBase()

    Initializes a new instance of the object class.

    Declaration
    protected MockerTestBase()

    MockerTestBase(Action<Mocker>)

    Declaration
    protected MockerTestBase(Action<Mocker> setupMocksAction)
    Parameters
    Type Name Description
    Action<Mocker> setupMocksAction

    MockerTestBase(Action<Mocker>, Action<TComponent>)

    Declaration
    protected MockerTestBase(Action<Mocker> setupMocksAction, Action<TComponent> createdComponentAction)
    Parameters
    Type Name Description
    Action<Mocker> setupMocksAction
    Action<TComponent> createdComponentAction

    MockerTestBase(Action<Mocker>, Action<TComponent>, params Type[])

    Initializes a new instance of the MockerTestBase<TComponent> class while combining mock setup, post-creation configuration, and explicit constructor selection.

    Declaration
    protected MockerTestBase(Action<Mocker> setupMocksAction, Action<TComponent> createdComponentAction, params Type[] createArgumentTypes)
    Parameters
    Type Name Description
    Action<Mocker> setupMocksAction

    The setup mocks action.

    Action<TComponent> createdComponentAction

    The created component action.

    Type[] createArgumentTypes

    Create component using constructor with matching types.

    Examples

    This overload is useful when a service has several constructors and the selected one needs additional state configured after creation.

    If the test uses Moq-only setup methods such as Setup(...) or ReturnsAsync(...), use the legacy Moq path intentionally and ensure the Moq provider is selected for that test assembly.

    public sealed class OrdersImportTests : MockerTestBase<OrdersImporter>
    {
        public OrdersImportTests()
            : base(
                setupMocksAction: mocker =>
                {
                    mocker.GetMock<IOrdersApi>()
                        .Setup(x => x.FetchPageAsync(1))
                        .ReturnsAsync(new OrdersPage());
                },
                createdComponentAction: component =>
                    component.BatchName = "nightly-import",
                createArgumentTypes: typeof(string))
        {
        }
    }

    Use GetOrCreateMock in constructor-focused tests only when you need the returned tracked mock object itself, such as keyed identity, provider options, resetting the tracked mock, or passing Instance into custom construction.

    MockerTestBase(Action<Mocker>, Func<Mocker, TComponent>)

    Declaration
    protected MockerTestBase(Action<Mocker> setupMocksAction, Func<Mocker, TComponent> createComponentAction)
    Parameters
    Type Name Description
    Action<Mocker> setupMocksAction
    Func<Mocker, TComponent> createComponentAction

    MockerTestBase(Action<Mocker>, Func<Mocker, TComponent>?, Action<TComponent>)

    Initializes a new instance of the MockerTestBase<TComponent> class with explicit hooks for arranging mocks, overriding construction, and applying post-creation setup.

    Declaration
    protected MockerTestBase(Action<Mocker> setupMocksAction, Func<Mocker, TComponent>? createComponentAction, Action<TComponent> createdComponentAction)
    Parameters
    Type Name Description
    Action<Mocker> setupMocksAction

    The action to set up the mocks before component creation.

    Func<Mocker, TComponent> createComponentAction

    The action to override component creation.

    Action<TComponent> createdComponentAction

    The action to do after the component is created.

    Examples

    Use this overload when the test base needs full control over the arrange, create, and post-create phases.

    GetOrCreateMock returns a provider-backed tracked mock handle. It works with the active FastMoq provider, but chaining Moq-specific setup APIs such as Setup(...) requires the Moq provider to be selected for the test assembly.

    public sealed class InvoiceServiceTests : MockerTestBase<InvoiceService>
    {
        public InvoiceServiceTests()
            : base(
                setupMocksAction: mocker =>
                {
                    mocker.GetMock<IExchangeRateClient>()
                        .Setup(x => x.GetRate("USD", "EUR"))
                        .Returns(0.92m);
                },
                createComponentAction: mocker =>
                    new InvoiceService(mocker.GetObject<IExchangeRateClient>(), "EUR"),
                createdComponentAction: component =>
                    component.Region = "EMEA")
        {
        }
    }

    Use GetOrCreateMock when you need the tracked mock handle itself, for example to pass Instance into custom construction without relying on automatic resolution, to reuse the same tracked mock across calls, or to use keyed MockRequestOptions. Use GetMock only for the legacy Moq-specific setup path.

    MockerTestBase(Action<TComponent>)

    Declaration
    protected MockerTestBase(Action<TComponent> createdComponentAction)
    Parameters
    Type Name Description
    Action<TComponent> createdComponentAction

    MockerTestBase(bool)

    Create instance and setting mock resolution. Mock resolution is on by default. When it is off, it may not be able to fill in properties or other injections of components.

    Declaration
    protected MockerTestBase(bool innerMockResolution)
    Parameters
    Type Name Description
    bool innerMockResolution

    MockerTestBase(Func<Mocker, TComponent>)

    Declaration
    protected MockerTestBase(Func<Mocker, TComponent> createComponentAction)
    Parameters
    Type Name Description
    Func<Mocker, TComponent> createComponentAction

    MockerTestBase(Func<Mocker, TComponent>, Action<TComponent>)

    Declaration
    protected MockerTestBase(Func<Mocker, TComponent> createComponentAction, Action<TComponent> createdComponentAction)
    Parameters
    Type Name Description
    Func<Mocker, TComponent> createComponentAction
    Action<TComponent> createdComponentAction

    MockerTestBase(params Type[])

    Create the component using the constructor whose parameter types match createArgumentTypes.

    Declaration
    protected MockerTestBase(params Type[] createArgumentTypes)
    Parameters
    Type Name Description
    Type[] createArgumentTypes
    Examples

    Use this overload when the component exposes multiple constructors and the test should target a specific signature.

    public sealed class ReportExporterTests : MockerTestBase<ReportExporter>
    {
        public ReportExporterTests()
            : base(typeof(string), typeof(int))
        {
        }
    }
    

    // FastMoq will choose a constructor such as: // ReportExporter(IStorageClient storageClient, string containerName, int retryCount)

    Properties

    Component

    Gets or sets the component under test.

    Declaration
    protected TComponent Component { get; set; }
    Property Value
    Type Description
    TComponent

    The service.

    ComponentCreationFlags

    Controls how the component under test is created by the default constructor path. Override this to opt into alternate constructor-selection or optional-parameter behavior for the component.

    Declaration
    protected virtual InstanceCreationFlags ComponentCreationFlags { get; }
    Property Value
    Type Description
    InstanceCreationFlags

    ConfigureMockerPolicy

    Allows a test base to configure grouped Mocker policy defaults before the component is created.

    Declaration
    protected virtual Action<MockerPolicyOptions>? ConfigureMockerPolicy { get; }
    Property Value
    Type Description
    Action<MockerPolicyOptions>

    CreateComponentAction

    Gets or sets the creation component action. This action is run whenever the component is created.

    Declaration
    protected virtual Func<Mocker, TComponent> CreateComponentAction { get; }
    Property Value
    Type Description
    Func<Mocker, TComponent>

    The action to override the component creation.

    CreatedComponentAction

    Gets or sets the created component action. This action is run after the component is created.

    Declaration
    protected virtual Action<TComponent>? CreatedComponentAction { get; }
    Property Value
    Type Description
    Action<TComponent>

    The created component action.

    CustomMocks

    Gets or sets the custom mocks. These are added whenever the component is created.

    Declaration
    protected IEnumerable<MockModel> CustomMocks { get; set; }
    Property Value
    Type Description
    IEnumerable<MockModel>

    The custom mocks.

    Mocks

    Gets the Mocker.

    Declaration
    protected Mocker Mocks { get; }
    Property Value
    Type Description
    Mocker

    The mocks.

    Scenario

    Gets a fluent scenario builder for the current component.

    Declaration
    protected ScenarioBuilder<TComponent> Scenario { get; }
    Property Value
    Type Description
    ScenarioBuilder<TComponent>

    SetupMocksAction

    Gets or sets the setup mocks action. This action is run before the component is created.

    Declaration
    protected virtual Action<Mocker>? SetupMocksAction { get; }
    Property Value
    Type Description
    Action<Mocker>

    The setup mocks action.

    Methods

    CreateComponent()

    Sets the Component property with a new instance while maintaining the constructor setup and any other changes.

    Declaration
    protected void CreateComponent()
    Examples

    Use CreateComponent() when you need to rebuild the component after changing test-base configuration that affects construction or post-creation state.

    private string CreatedChannel { get; set; } = "default";
    

    protected override Action<OrderSubmitter> CreatedComponentAction => component => component.SubmissionChannel = CreatedChannel;

    [Fact] public void Recreates_component_after_changing_created_state() { CreatedChannel = "priority";

    CreateComponent();
    
    Component.SubmissionChannel.Should().Be("priority");
    

    }

    Dispose()

    Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

    Declaration
    public void Dispose()

    Dispose(bool)

    Releases unmanaged and - optionally - managed resources.

    Declaration
    protected virtual void Dispose(bool disposing)
    Parameters
    Type Name Description
    bool disposing

    true to release both managed and unmanaged resources; false to release only unmanaged resources.

    GetConstructor()

    Gets the constructor.

    Declaration
    protected ConstructorInfo GetConstructor()
    Returns
    Type Description
    ConstructorInfo

    ConstructorInfo of the constructor.

    Exceptions
    Type Condition
    TypeAccessException

    Error finding the constructor used to create the component.

    LoggingCallback(LogLevel, EventId, string)

    Receives log entries emitted through the current Mocker instance. Override this in a derived test base when log output should be captured or redirected.

    Declaration
    public virtual void LoggingCallback(LogLevel logLevel, EventId eventId, string message)
    Parameters
    Type Name Description
    LogLevel logLevel

    The log severity.

    EventId eventId

    The event identifier.

    string message

    The formatted log message.

    LoggingCallback(LogLevel, EventId, string, Exception?)

    Receives log entries and any attached exception emitted through the current Mocker instance. Override this overload when tests need exception-aware log capture.

    Declaration
    public virtual void LoggingCallback(LogLevel logLevel, EventId eventId, string message, Exception? exception)
    Parameters
    Type Name Description
    LogLevel logLevel

    The log severity.

    EventId eventId

    The event identifier.

    string message

    The formatted log message.

    Exception exception

    The exception associated with the log entry, if any.

    TestAllConstructorParameters(Action<Action, string, string>, Func<ParameterInfo, object?>?, Func<ParameterInfo, object?>?, BindingFlags)

    Tests all constructor parameters.

    Declaration
    protected void TestAllConstructorParameters(Action<Action, string, string> createAction, Func<ParameterInfo, object?>? defaultValue = null, Func<ParameterInfo, object?>? validValue = null, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public)
    Parameters
    Type Name Description
    Action<Action, string, string> createAction

    The action used for each parameter of each constructor.

    Func<ParameterInfo, object> defaultValue

    The default value used when testing the parameter.

    Func<ParameterInfo, object> validValue

    The valid value used when not testing the parameter.

    BindingFlags bindingFlags

    The binding flags.

    TestConstructorParameters(Action<Action, string, string>, Func<ParameterInfo, object?>?, Func<ParameterInfo, object?>?)

    Tests the active constructor parameters for the current component and lets the test assert what should happen when each parameter is replaced with an invalid value.

    Declaration
    protected void TestConstructorParameters(Action<Action, string, string> createAction, Func<ParameterInfo, object?>? defaultValue = null, Func<ParameterInfo, object?>? validValue = null)
    Parameters
    Type Name Description
    Action<Action, string, string> createAction

    The create action.

    Func<ParameterInfo, object> defaultValue

    The default value.

    Func<ParameterInfo, object> validValue

    The valid value.

    Examples

    Use TestConstructorParameters(Action<Action, string, string>, Func<ParameterInfo, object?>?, Func<ParameterInfo, object?>?) to verify guard clauses on the constructor that FastMoq actually selected for TComponent.

    [Fact]
    public void CheckoutService_ShouldThrowForNullDependencies() => TestConstructorParameters(
        (action, constructorName, parameterName) =>
        {
            action
                .Should()
                .Throw<ArgumentNullException>()
                .WithMessage($"*{parameterName}*");
        });

    Provide explicit invalid and valid values when constructor arguments need type-specific test data instead of the default FastMoq resolution behavior.

    [Fact]
    public void ImportJob_ShouldValidateConstructorArguments() => TestConstructorParameters(
        (action, constructorName, parameterName) =>
        {
            action
                .Should()
                .Throw<ArgumentException>()
                .WithMessage($"*{parameterName}*");
        },
        info => info.Name switch
        {
            "tenant" => string.Empty,
            "batchSize" => 0,
            _ => default,
        },
        info => info.Name switch
        {
            "tenant" => "contoso",
            "batchSize" => 50,
            _ => Mocks.GetObject(info.ParameterType),
        });

    TestConstructorParameters(ConstructorInfo, Action<Action, string, string>, Func<ParameterInfo, object?>?, Func<ParameterInfo, object?>?)

    Tests the constructor parameters.

    Declaration
    protected void TestConstructorParameters(ConstructorInfo constructorInfo, Action<Action, string, string> createAction, Func<ParameterInfo, object?>? defaultValue = null, Func<ParameterInfo, object?>? validValue = null)
    Parameters
    Type Name Description
    ConstructorInfo constructorInfo

    The constructor information.

    Action<Action, string, string> createAction

    The create action.

    Func<ParameterInfo, object> defaultValue

    The value replaced when testing a parameter.

    Func<ParameterInfo, object> validValue

    The valid value.

    WaitFor<T>(Func<T>)

    Waits for an action.

    Declaration
    public static T WaitFor<T>(Func<T> logic)
    Parameters
    Type Name Description
    Func<T> logic

    The action.

    Returns
    Type Description
    T

    T.

    Type Parameters
    Name Description
    T
    Exceptions
    Type Condition
    ArgumentNullException

    logic

    WaitFor<T>(Func<T>, TimeSpan)

    Waits for an action.

    Declaration
    public static T WaitFor<T>(Func<T> logic, TimeSpan timespan)
    Parameters
    Type Name Description
    Func<T> logic

    The action.

    TimeSpan timespan

    The timespan, defaults to 4 seconds.

    Returns
    Type Description
    T

    T.

    Type Parameters
    Name Description
    T
    Exceptions
    Type Condition
    ArgumentNullException

    logic

    WaitFor<T>(Func<T>, TimeSpan, TimeSpan)

    Waits for an action.

    Declaration
    public static T WaitFor<T>(Func<T> logic, TimeSpan timespan, TimeSpan waitBetweenChecks)
    Parameters
    Type Name Description
    Func<T> logic

    The action.

    TimeSpan timespan

    The maximum time to wait.

    TimeSpan waitBetweenChecks

    Time between each check.

    Returns
    Type Description
    T

    T.

    Type Parameters
    Name Description
    T

    Logic of T.

    Exceptions
    Type Condition
    ArgumentNullException

    logic

    ApplicationException

    Timeout waiting for condition

    Implements

    IDisposable

    Extension Methods

    ObjectExtensions.RaiseIfNull<T>(T?, string?, string?, int?, string?)
    TestClassExtensions.GetFieldValue<TObject>(TObject, string, TObject?)
    TestClassExtensions.GetField<TObject>(TObject, string)
    TestClassExtensions.GetMemberName<T, TValue>(T, Expression<Func<T, TValue>>)
    TestClassExtensions.GetMember<T, TValue>(T, Expression<Func<T, TValue>>)
    TestClassExtensions.GetMethodValue<TObject>(TObject, string, object?, params object[])
    TestClassExtensions.GetMethod<TObject>(TObject, string)
    TestClassExtensions.GetPropertyValue<TObject>(TObject, string, object?)
    TestClassExtensions.GetProperty<TObject>(TObject, string)
    TestClassExtensions.SetFieldValue<TObject>(TObject, string, object?)
    TestClassExtensions.SetPropertyValue<TObject>(TObject, string, object?)
    MockerHttpMoqExtensions.SetupHttpMessage(object, Func<HttpResponseMessage>, Expression?, Expression?)
    MockerHttpMoqExtensions.SetupMessageAsync<TMock, TReturn>(object, Expression<Func<TMock, Task<TReturn>>>, Func<TReturn>)
    MockerHttpMoqExtensions.SetupMessageProtectedAsync<TMock, TReturn>(object, string, Func<TReturn>, params object?[]?)
    MockerHttpMoqExtensions.SetupMessageProtected<TMock, TReturn>(object, string, Func<TReturn>, params object?[]?)
    MockerHttpMoqExtensions.SetupMessage<TMock, TReturn>(object, Expression<Func<TMock, TReturn>>, Func<TReturn>)
    TestClassExtensions.GetFieldInfo<TType>(object, string)
    TestClassExtensions.GetFieldValue<T>(object?, FieldInfo)
    TestClassExtensions.GetFieldValue<T, TType>(object, string)
    In this article
    Back to top
    Generated 2026-04-08 00:16 UTC