Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generic method setups of parent types invoked #1498

Open
rkkr opened this issue Aug 23, 2024 · 0 comments
Open

Generic method setups of parent types invoked #1498

rkkr opened this issue Aug 23, 2024 · 0 comments
Labels

Comments

@rkkr
Copy link

rkkr commented Aug 23, 2024

Describe the Bug

We want to test a generic function that has multiple invocations of related types. In the test below exception Unable to cast object of type 'Foo' to type 'Bar' is thrown at line mock.Object.Create<Bar>() because x.Create<Foo> setup was invoked. mock.Object.Create<Foo>() also invokes x.Create<Foo>.

Steps to Reproduce

    public class Foo;
    public class Bar : Foo { };

    public interface ICreator 
        {
        T Create<T> ();
        }

    [TestClass]
    public class Test
        {
        [TestMethod]
        public void WrongSetup ()
            {
            var mock = new Mock<ICreator>(MockBehavior.Strict);

            mock.Setup(x => x.Create<Bar>()).Returns(new Bar());
            mock.Setup(x => x.Create<Foo>()).Returns(new Foo());
            
            var bar = mock.Object.Create<Bar>();
            }
        }

Expected Behavior

Default generics setup behavior seems to work like It.IsSubtype<T>. It should default to strict match. If loose match is needed It.IsSubtype<T> can be used.

Exception with Stack Trace

ICreatorProxy.Create[T]()
Test.WrongSetup() line 32
RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)

Version Info

4.20.70

Additional Info

Setups can be reversed to make the test pass as child setup is then matched first, but this is not a usable workaround.

Back this issue
Back this issue

@rkkr rkkr added the bug label Aug 23, 2024
@rkkr rkkr changed the title Generic methos setups of child types invoked Generic method setups of child types invoked Aug 23, 2024
@rkkr rkkr changed the title Generic method setups of child types invoked Generic method setups of parent types invoked Aug 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant