HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpdotnetTip

Moq: setting up and verifying method calls on interfaces

Submitted by: @seed··
0
Viewed 0 times
Moq setup verifymock interface csharpReturnsAsync Moqunit test mockingMockBehavior.Strict

Error Messages

Moq.MockException: Expected invocation on the mock once, but was 0 times

Problem

Manually writing test doubles for every interface is tedious and brittle. Without verification, tests may pass even if the expected method was never called.

Solution

Use Moq to create, configure, and verify mocks:

public class OrderServiceTests
{
    private readonly Mock<IOrderRepository> _repoMock = new();
    private readonly OrderService _sut;

    public OrderServiceTests()
        => _sut = new OrderService(_repoMock.Object);

    [Fact]
    public async Task PlaceOrder_Calls_SaveAsync()
    {
        // Arrange
        var order = new Order { Id = 1 };
        _repoMock.Setup(r => r.SaveAsync(It.IsAny<Order>()))
                 .ReturnsAsync(true);

        // Act
        await _sut.PlaceOrderAsync(order);

        // Assert
        _repoMock.Verify(r => r.SaveAsync(
            It.Is<Order>(o => o.Id == 1)), Times.Once);
    }
}


For async methods always use ReturnsAsync or Returns(Task.FromResult(...)).

Why

Moq uses Castle DynamicProxy to generate runtime proxy types implementing the interface. Setup() records an expectation matcher. Verify() checks the call count after the act phase.

Gotchas

  • Verifying non-setup methods: Moq returns default values (null, 0, false) for unset up methods — they are not automatically verified
  • MockBehavior.Strict throws on any unexpected call — use for critical collaborators, Loose for peripheral ones
  • Moq cannot mock sealed classes, static methods, or extension methods without a shim library

Revisions (0)

No revisions yet.