Skip to main content

Lesson 2 of 8

Moq - Mocking Dependencies

Moq creates fake implementations of interfaces so you can test classes in isolation without real databases, HTTP services, or email providers. You control what the mock returns and verify it was called correctly.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Setup, Verify & Argument Matchers

Setup, Verify & Argument Matchers
using Moq;
using FluentAssertions;

public class ProductServiceTests
{
    // ━━ Setup: create mocks ━━
    private readonly Mock<IProductRepository> _repoMock = new();
    private readonly Mock<IMapper> _mapperMock = new();
    private readonly Mock<ILogger<ProductService>> _loggerMock = new();
    private readonly Mock<IMediator> _mediatorMock = new();
    private readonly Mock<IValidator<CreateProductRequest>> _validatorMock = new();

    private ProductService CreateSut() => new(
        new UnitOfWorkFake(_repoMock.Object),
        _mapperMock.Object,
        _validatorMock.Object,
        _mediatorMock.Object,
        _loggerMock.Object);

    [Fact]
    public async Task CreateAsync_ValidRequest_ReturnsSuccessResult()
    {
        // ━━ Arrange ━━
        var request = new CreateProductRequest("Widget", 9.99m, "USD", Guid.NewGuid(), 100, null);
        var entity = new ProductEntity { Id = Guid.NewGuid(), Name = "Widget", Price = 9.99m };
        var dto = new ProductDto(entity.Id, "Widget", "widget", 9.99m, "USD", "Electronics", 100, true, DateTime.UtcNow);

        // Setup validation to pass
        _validatorMock
            .Setup(v => v.ValidateAsync(request, It.IsAny<CancellationToken>()))
            .ReturnsAsync(new ValidationResult { IsValid = true, Errors = [] });

        // Setup slug uniqueness check
        _repoMock
            .Setup(r => r.SlugExistsAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
            .ReturnsAsync(false);

        // Setup mapping
        _mapperMock.Setup(m => m.Map<ProductEntity>(request)).Returns(entity);
        _mapperMock.Setup(m => m.Map<ProductDto>(entity)).Returns(dto);

        // Setup mediator publish (void-like)
        _mediatorMock
            .Setup(m => m.Publish(It.IsAny<object>(), It.IsAny<CancellationToken>()))
            .Returns(Task.CompletedTask);

        var sut = CreateSut();

        // ━━ Act ━━
        var result = await sut.CreateAsync(request, CancellationToken.None);

        // ━━ Assert ━━
        result.IsSuccess.Should().BeTrue();
        result.Value.Should().NotBeNull();
        result.Value!.Name.Should().Be("Widget");

        // Verify repository.Add was called exactly once with the entity
        _repoMock.Verify(r => r.Add(entity), Times.Once);

        // Verify event was published
        _mediatorMock.Verify(
            m => m.Publish(It.IsAny<ProductCreatedEvent>(), It.IsAny<CancellationToken>()),
            Times.Once);
    }

    [Fact]
    public async Task CreateAsync_DuplicateSlug_ReturnsConflict()
    {
        var request = new CreateProductRequest("Duplicate", 5m, "USD", Guid.NewGuid(), 10, null);

        _validatorMock.Setup(v => v.ValidateAsync(request, It.IsAny<CancellationToken>()))
            .ReturnsAsync(new ValidationResult { IsValid = true, Errors = [] });

        // Slug already exists
        _repoMock.Setup(r => r.SlugExistsAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
            .ReturnsAsync(true);

        var sut = CreateSut();
        var result = await sut.CreateAsync(request, CancellationToken.None);

        result.IsSuccess.Should().BeFalse();
        result.ErrorType.Should().Be(ResultErrorType.Conflict);

        // Verify Add was NEVER called (conflict short-circuits)
        _repoMock.Verify(r => r.Add(It.IsAny<ProductEntity>()), Times.Never);
    }

    [Fact]
    public async Task CreateAsync_InvalidRequest_ReturnsValidation()
    {
        var request = new CreateProductRequest("", -1m, "USD", Guid.Empty, 0, null);

        _validatorMock.Setup(v => v.ValidateAsync(request, It.IsAny<CancellationToken>()))
            .ReturnsAsync(new ValidationResult
            {
                IsValid = false,
                Errors = [new ValidationFailure("Name", "Name is required"), new ValidationFailure("Price", "Price must be > 0")]
            });

        var result = await (CreateSut()).CreateAsync(request, CancellationToken.None);

        result.IsSuccess.Should().BeFalse();
        result.ErrorType.Should().Be(ResultErrorType.Validation);
        result.Error.Should().Contain("Name is required");
    }
}

// Stub types
class ProductService { public ProductService(object _, object __, object ___, object ____, object _____) { } public Task<Result<ProductDto>> CreateAsync(CreateProductRequest r, CancellationToken ct) => Task.FromResult(Result<ProductDto>.Success(new ProductDto(Guid.NewGuid(), r.Name, "", r.Price, r.CurrencyCode, "", r.InitialStock, true, DateTime.UtcNow))); }
class UnitOfWorkFake(IProductRepository r) { }
record Result<T>(bool IsSuccess, T? Value, string? Error, ResultErrorType ErrorType) { public static Result<T> Success(T v) => new(true, v, null, default); }
enum ResultErrorType { Validation, Conflict, NotFound }
record ProductCreatedEvent(Guid Id, string Name);
class ValidationResult { public bool IsValid { get; set; } public System.Collections.Generic.List<ValidationFailure> Errors { get; set; } = []; }
class ValidationFailure { public ValidationFailure(string p, string e) { PropertyName = p; ErrorMessage = e; } public string PropertyName { get; set; } = ""; public string ErrorMessage { get; set; } = ""; }
interface IValidator<T> { Task<ValidationResult> ValidateAsync(T v, CancellationToken ct); }
interface IProductRepository { Task<bool> SlugExistsAsync(string slug, CancellationToken ct = default); void Add(ProductEntity p); }
class ProductEntity { public Guid Id { get; set; } public string Name { get; set; } = ""; public decimal Price { get; set; } }
record ProductDto(Guid Id, string Name, string Slug, decimal Price, string CurrencyCode, string CategoryName, int StockQuantity, bool IsAvailable, DateTime CreatedAt);
record CreateProductRequest(string Name, decimal Price, string CurrencyCode, Guid CategoryId, int InitialStock, string? Description);
interface IMapper { TDest Map<TDest>(object src); }
interface IMediator { Task Publish(object n, CancellationToken ct); }
interface ILogger<T> { }

Tip

Tip

Practice Moq Mocking Dependencies in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Moq Mocking Dependencies from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Moq Mocking Dependencies is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done