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

Setup a method with argument of interface type doesn't work when a not null instance is passed to that method #1172

Closed
jsayari opened this issue Jun 18, 2021 · 0 comments

Comments

@jsayari
Copy link

jsayari commented Jun 18, 2021

I am trying to setup a method which accepts a parameter of an interface type. To make it clear suppose that I am mocking the following IFoo interface and its DoSomething method accept parameter of IBar interface:

public interface IFoo
{
     int DoSomething(IBar bar);
}
public class Bar : IBar
{
}

Then setting up the IFoo mocking object as:

var moqObject = new Moq<IFoo>();
moqObject.Setup(x => x.DoSomething(It.IsAny<IBar>())).Returns(() => 10);

When calling DoSomething method of the moq object with null argument it works correctly and returns 10 as it was set up but when call it with a new instance of Bar it doesn't go into the Returns part.

moqObject.Object.DoSomething(null);//this returns 10 and works as expected
moqObject.Object.DoSomething(new Bar()); //this doesn't enter the Rerturns part of the moqObject

But if I cast the Bar object into IBar it works correctly

moqObject.Object.DoSomething((IBar)new Bar());//this returns 10 as well

Anything wrong with my mocking object setup? or this behavior is by design?

@jsayari jsayari closed this as completed Jun 18, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant