Moq
unit testing
C#
method verification
mocking

How do I verify a method was called exactly once with Moq?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In unit testing, it is common to check that certain methods on a mock object were called under specific conditions. The `Moq` library for .NET is a popular choice for creating mock objects during tests. One powerful feature of `Moq` is the ability to verify that a method was called a specific number of times, providing confidence that your code interacts with dependencies correctly.

This article explores how to verify that a method was called exactly once using `Moq`. We'll delve into technical aspects of this verification process with examples, best practices, and additional considerations.

Understanding Moq

`Moq` is a versatile mocking framework for .NET that allows developers to mock interfaces and classes in unit tests. By creating mock objects, you can test the interactions between your unit of work and its dependencies without relying on their actual implementations.

Key Features of Moq

  • Setup: Define behavior for mock methods/properties.
  • Verify: Confirm that certain methods were called with expected parameters and specific invocation counts.
  • Flexibility: Allows for verification with a wide range of conditions using lambda expressions and various verification options.

Code Example: Verifying Method Call

To illustrate the process of verifying that a method was called exactly once, let's use a simple example with a `Calculator` service interface:

  • Arrange: Create a mock for `ICalculatorService` and instantiate the `CalculationHandler` with the mock object.
  • Act: Call the `Process` method on `CalculationHandler`.
  • Assert: Use `Verify` with the `Times.Once` parameter on the mocked service to ensure the `Calculate` method was called exactly once.
  • `Verify` Method: Used to check that a specific method was called with the expected parameters and invocation count.
  • `Times.Once`: A built-in `Moq` method indicating that the interaction should occur exactly once.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.