devlooped/moq · error · ArgumentOutOfRangeException

ArgumentOutOfRangeException: callCount

Error message

ArgumentOutOfRangeException: callCount ('{0}' value must be greater than or equal to '1').

What it means

Times.AtLeast(callCount) requires a minimum count of at least 1; passing a smaller value throws ArgumentOutOfRangeException named callCount. AtLeast(0) is meaningless — use Times.Never for zero expected calls.

Solutions

  1. Ensure the value passed is >= 1 (clamp or validate before calling)
  2. Use Times.Never instead of AtLeast(0) when zero calls should be asserted
  3. Guard computed values: if (n < 1) n = 1; or branch to Times.Never

Example fix

// before
mock.Verify(m => m.Foo(), Times.AtLeast(count)); // count may be 0
// after
mock.Verify(m => m.Foo(), count < 1 ? Times.Never : Times.AtLeast(count));
Defensive patterns

Strategy: validation

Validate before calling

if (minCalls >= 1)
    mock.Verify(m => m.Foo(), Times.AtLeast(minCalls));
else
    mock.Verify(m => m.Foo(), Times.Never);

Prevention

When it happens

Trigger: Calling Times.AtLeast(0) or Times.AtLeast(negative), directly or via Verify(..., Times.AtLeast(0)) or a minCount derived from a variable/computation that can be 0.

Common situations: Computing the minimum from config or a counter that is 0 when nothing happened; typos writing AtLeast where Never was intended.

Related errors


AI-assisted analysis of devlooped/moq@89a5be629c (2026-09-16). Data as JSON: /api/errors/e1c936da96c9504a. Report an issue: GitHub.

Appendix: source

Thrown at src/Moq/Times.cs:65

            }
            else
            {
                from = this.from;
                to = this.to;
            }
        }

        /// <summary>
        ///   Specifies that a mocked method should be invoked <paramref name="callCount"/> times
        ///   as minimum.
        /// </summary>
        /// <param name="callCount">The minimum number of times.</param>
        /// <returns>An object defining the allowed number of invocations.</returns>
        public static Times AtLeast(int callCount)
        {
            if (callCount < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(callCount));
            }

            return new Times(Kind.AtLeast, callCount, int.MaxValue);
        }

        /// <summary>
        ///   Specifies that a mocked method should be invoked one time as minimum.
        /// </summary>
        /// <returns>An object defining the allowed number of invocations.</returns>
        public static Times AtLeastOnce()
        {
            return new Times(Kind.AtLeastOnce, 1, int.MaxValue);
        }

        /// <summary>
        ///   Specifies that a mocked method should be invoked <paramref name="callCount"/> times
        ///   as maximum.
        /// </summary>

View on GitHub (pinned to 89a5be629c)