Skip to content

IProtectedMock fails on a new virtual methods #1341

@VladimirKhvostov

Description

@VladimirKhvostov

This regression was introduced in v4.7.0 (tested with 4.5.30 - no issues).

Consider the following example:

namespace LibraryTests
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Moq;
    using Moq.Protected;

    public class DataReader
    {
        protected virtual List<string> ExecuteReader() => throw new NotImplementedException();
    }

    public class AdvancedReader : DataReader
    {
        protected new virtual IList<string> ExecuteReader() => base.ExecuteReader();
    }

    [TestClass]
    public class ProtectedTests
    {
        [TestMethod]
        public void Test1()
        {
            Mock<AdvancedReader> mock = new Mock<AdvancedReader>();
            mock.Protected().Setup<IList<string>>("ExecuteReader").Returns(new List<string>() { "1", "2", "3" });
        }
    }
}

Setup fails with the following error:
System.InvalidOperationException: 'Sequence contains more than one matching element'
Stack:

System.Core.dll!System.Linq.Enumerable.SingleOrDefault<System.Reflection.MethodInfo>(System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo> source, System.Func<System.Reflection.MethodInfo, bool> predicate)	Unknown
Moq.dll!Moq.Protected.ProtectedMock<LibraryTests.AdvancedReader>.InternalSetup<System.Collections.Generic.IList<string>>(string methodName, System.Type[] genericTypeArguments, bool exactParameterMatch, object[] args)	Unknown
Moq.dll!Moq.Protected.ProtectedMock<LibraryTests.AdvancedReader>.Setup<System.Collections.Generic.IList<string>>(string methodName, object[] args)	Unknown

Since ExecuteReader in the AdvancedReader class is a new virtual method, I believe reflection returned 2 MethodInfo objects and Moq expects one or zero.

Back this issue
Back this issue

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions