moq icon indicating copy to clipboard operation
moq copied to clipboard

IProtectedMock fails on a new virtual methods

Open VladimirKhvostov opened this issue 2 years ago • 1 comments

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

VladimirKhvostov avatar May 09 '23 16:05 VladimirKhvostov

Due to lack of recent activity, this issue has been labeled as 'stale'. It will be closed if no further activity occurs within 30 more days. Any new comment will remove the label.

github-actions[bot] avatar Aug 24 '24 20:08 github-actions[bot]

Due to lack of recent activity, this issue has been labeled as 'stale'. It will be closed if no further activity occurs within 30 more days. Any new comment will remove the label.

github-actions[bot] avatar Apr 04 '25 01:04 github-actions[bot]

This issue will now be closed since it has been labeled 'stale' without activity for 30 days.

github-actions[bot] avatar May 05 '25 01:05 github-actions[bot]