This directory contains the sample documentation and executable examples that currently exist in this repository.
- E-Commerce Order Processing - Full sample documentation for an order-processing workflow
- Executable Testing Examples - Smaller repo-local service examples backed by the
FastMoq.TestingExampleproject
If you want smaller service-focused examples that compile and run directly in this repository, start with Executable Testing Examples.
Those examples are backed by the FastMoq.TestingExample project and currently show:
MockerTestBase<TComponent>in realistic service tests- built-in
IFileSystembehavior withMockFileSystem - tracked
GetOrCreateMock<T>()usage versus detachedCreateStandaloneFastMock<T>()when a test needs an extra same-type double or manual wiring VerifyLogged(...)assertions- fluent
Scenario.With(...).When(...).Then(...).Verify(...)usage insideMockerTestBase<TComponent> - provider-first verification with
TimesSpec.Once,TimesSpec.NeverCalled,TimesSpec.Exactly(...),TimesSpec.AtLeast(...), andTimesSpec.AtMost(...)
- Azure Service Bus integration and testing
- Azure Blob Storage operations
- Azure Key Vault configuration
- Entity Framework Core with Azure SQL
- HttpClient and external API integration
- Background Services and hosted services
- Blazor Components testing
- API Controllers with complex dependencies
- Configuration and Options patterns
- Logging and Monitoring integration
The sample test projects intentionally showcase FastMoq extension helpers so you can apply them directly:
CreateHttpClient()to quickly use FastMoq's built-inHttpClientpath; a lightweightIHttpClientFactoryis available for simpleCreateClient(...)flows without per-name configuration, and later helper calls update that built-in factory path. Resolve or inject that built-in factory as an object instead of callingGetOrCreateMock<IHttpClientFactory>()unless you intentionally want to replace it.- Prefer
WhenHttpRequest(...)andWhenHttpRequestJson(...)for provider-neutral request matching and response setup. - Use
SetupHttpMessage(...)only when you intentionally need Moq-specific protectedSendAsyncbehavior from the Moq provider package. Keepusing FastMoq.Extensions;, addFastMoq.Provider.Moq, and select the Moq provider for the test assembly when you use that compatibility path. - Content helpers:
GetStringContent,GetContentBytesAsync(),GetContentStreamAsync()for asserting raw payloads.
GetMockDbContext<TContext>()to obtain a mock context with DbSets auto‑prepared.- Add a custom variant via
AddTypeif you want to pin a specific test-time implementation.
- Prefer
Mocks.VerifyLogged(LogLevel.Information, "Message")for provider-safe logger assertions. - Use
GetOrCreateMock<ILogger<T>>().AsMoq().VerifyLogger(...)only when you intentionally need the legacy Moq-specific compatibility behavior, such as minimizing churn in older Moq-shaped tests during the v4 transition. It is not the preferred path for new assertions just because you want more control; preferVerifyLogged(...)unless you specifically need the old Moq-only assertion surface.
CreateInstance<T>()/ typed overloads pick the correct constructor and auto‑inject mocks.CreateStandaloneFastMock<T>()gives you a detached provider-first double for manual wiring;CreateFastMock<T>()registers a tracked mock in the currentMockerand should be used only when that tracked registration is the intent.AddType<TAbstraction>(factory)to pin specific concrete/instance values (e.g., seededUrior options).
Even when not running in Azure, the samples demonstrate how you would substitute Azure types:
- Wrap Azure SDK clients with interfaces in your application layer and mock those interfaces in tests.
- Use consistent naming for senders/processors so verification (e.g., Service Bus send) is easy.
If you adapt these samples for Azure Functions HTTP triggers, prefer the first-party helpers in FastMoq.AzureFunctions.Extensions instead of hand-rolled MockedHttpRequestData or MockedHttpResponseData utilities when possible:
- Build the request with
CreateHttpRequestData(...): supply method, route values, headers, claims, query-string values, and JSON body. - Provide dependency injection values using
AddType(...),AddServiceProvider(...), orAddFunctionContextInstanceServices(...)when the function resolves framework services. - Use
WhenHttpRequest(...)orWhenHttpRequestJson(...)for outboundHttpClientcalls triggered inside the function. - Assert:
- Outbound calls (verify
SendAsync) - Response status and body (
ReadBodyAsStringAsync(...)orReadBodyAsJsonAsync<T>(...)) - Logs via
VerifyLogged(...)
- Outbound calls (verify
Recommended layering:
using FastMoq.AzureFunctions.Extensions;
var request = Mocks.CreateHttpRequestData(builder => builder
.WithMethod("POST")
.WithUrl("http://test.com/api/Run?mode=sample")
.WithJsonBody(payload));
var result = await Component.RunAsync(request, CancellationToken.None);
var body = await result.ReadBodyAsStringAsync();
Mocks.VerifyLogged(LogLevel.Information, "Processed event");The Azure Functions helper package now supplies:
- Concrete
HttpRequestDataandHttpResponseDatabuilders for HTTP-trigger tests. - Automatic
FunctionContext.InstanceServicessetup with worker defaults. - Body readers that rewind request and response streams after assertions.
- The same provider-neutral logger and
HttpClienthelpers used elsewhere in FastMoq.
Some sample categories mentioned elsewhere in the documentation are future sample directions rather than folders that currently exist in this repository. Use this page and the linked directories above as the source of truth for what is available today.
The current samples are intentionally focused. Consider extending locally with:
- Adding a payment gateway client abstraction and testing retry/backoff logic via provider-neutral request helpers for happy-path routing, then Moq
SetupSequence(...)only when you intentionally need provider-specific call sequencing. - Adding blob metadata assertions using a mocked
BlobClient. - Introducing an options reload test using
IOptionsMonitor<T>+ updated values viaAddType.
| Goal | Helper | Notes |
|---|---|---|
| Fast default HttpClient | CreateHttpClient() |
Uses the built-in handler; lightweight factory compatibility is available without per-name configuration |
| Custom per‑test HTTP behavior | WhenHttpRequest() / WhenHttpRequestJson() |
Provider-neutral request matching and response setup |
| Mock EF Core context | GetMockDbContext<T>() |
Auto sets up DbSets; seed data before use |
| Extra independent same-type double | CreateStandaloneFastMock<T>() |
Detached provider-first mock; does not register into the current Mocker |
| Replace concrete dependency | AddType<T>() |
Pin deterministic instances (e.g., clock) |
| Verify log message | VerifyLogged(...) |
Provider-safe assertion over captured ILogger entries |
| Extract HTTP content | GetStringContent |
Use for string assertions |
Tip: Prefer the provider-neutral HTTP helpers first; drop down to Moq-specific setup only for protected-member or sequencing edge cases.
Start with Executable Testing Examples if you want the quickest path to real, runnable tests in this repository. Use E-Commerce Order Processing when you want a larger sample walkthrough.
- .NET 8.0 or later
- Azure subscription (for cloud features)
- Docker Desktop (optional, for containerized development)
- Visual Studio 2022 or VS Code
- Clone the repository
- Navigate to a sample directory
- Follow the sample-specific README
- Run the tests to see FastMoq in action
cd docs/samples/ecommerce-orders
dotnet restore
dotnet testFor the smaller executable examples instead:
dotnet test .\FastMoq.TestingExample\FastMoq.TestingExample.csprojAfter exploring these samples, you'll understand how to:
- Structure tests for complex, real-world applications
- Mock Azure services and external dependencies
- Test asynchronous and background operations
- Verify logging and monitoring behavior
- Handle configuration and secrets in tests
- Test web applications and APIs comprehensively
- Implement integration testing strategies
If you have questions about the samples or need help adapting them to your specific use case, please:
- Check the individual sample README files
- Review the main documentation
- Open an issue on the FastMoq repository