devlooped/moq · error · ArgumentException

Resources.InvalidMockGetType (formatted with typeof(T).Name…

Error message

Resources.InvalidMockGetType (formatted with typeof(T).Name and mocked type list)

What it means

Mock.Get<T>(mocked) retrieves the Mock<T> object behind a mock instance. This ArgumentException is thrown when the requested T is not part of the mock's type graph — the instance is a mock, but not for (or assignable through) the requested type, since .NET generics do not support covariance here. The message lists T and the types the mock actually implements.

Solutions

  1. Request the same type the mock was created with (Mock.Get<IFoo>(mockOfIFoo))
  2. If you need another interface, register it first with mock.As<IOther>() and then call Mock.Get<IOther>
  3. Create a separate Mock<T> for the additional type instead of reusing this instance
  4. Check the types listed in the message to see which interfaces the mock actually implements

Example fix

// before
var mock = new Mock<IFoo>();
var m = Mock.Get<IBar>(mock.Object); // IBar not implemented by this mock
// after
mock.As<IBar>();
var m = Mock.Get<IBar>(mock.Object);
Defensive patterns

Strategy: try-catch

Validate before calling

static bool CanGetMock<T>(object mocked)
{
    return mocked is IMocked m && m.Mock.ImplementsInterface(typeof(T));
}

Type guard

static bool IsMockOfType<T>(object instance)
    => instance is IMocked m && m.Mock.ImplementsInterface(typeof(T));

Try / catch

try
{
    var mock = Mock.Get<IFoo>(obj);
}
catch (ArgumentException ex) when (ex.Message.Contains(typeof(IFoo).Name))
{
    // the mock was not created for/As<T>'d to IFoo — register or create it
    throw;
}

Prevention

When it happens

Trigger: Mock.Get<SomeOtherInterface>(mockOfIFoo) where the mock was not created for or As<T>'d to that interface; calling Mock.Get on the class-mocked type when only interfaces were mocked; requesting a derived type from a base-type mock.

Common situations: Passing a mock instance to helper code typed with a different interface; after refactoring, requesting the concrete type when the mock was created from an interface; forgetting a required mock.As<T>() registration.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


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

Appendix: source

Thrown at src/Moq/Mock.cs:101

                // Alternatively, we may have been asked 
                // for a type that is assignable to the 
                // one for the mock.
                // This is not valid as generic types 
                // do not support covariance on 
                // the generic parameters.
                var imockedType = mocked.GetType().GetInterfaces().Single(i => i.Name.Equals("IMocked`1", StringComparison.Ordinal));
                var mockedType = imockedType.GetGenericArguments()[0];
                var types = string.Join(
                    ", ",
                    new[] { mockedType }
                        // Ignore internally defined IMocked<T>
                        .Concat(mock.InheritedInterfaces)
                        .Concat(mock.AdditionalInterfaces)
                        .Select(t => t.Name)
                        .ToArray());

                throw new ArgumentException(string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.InvalidMockGetType,
                    typeof(T).Name,
                    types));
            }

            throw new ArgumentException(Resources.ObjectInstanceNotMock, "mocked");
        }

        /// <summary>
        ///   Verifies that all verifiable expectations have been met.
        /// </summary>
        /// <exception cref="MockException">Not all verifiable expectations were met.</exception>
        public static void Verify(params Mock[] mocks)
        {
            foreach (var mock in mocks)
            {
                mock.Verify();

View on GitHub (pinned to 89a5be629c)