Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq - Setup Property to return string from method parameter

Tags:

.net

mocking

moq

I'm trying to do the following:

mockObject.Setup( a => a.MyObject.MyMethod( It.IsAny<string>() ).MyProperty ).Returns( ?? );

where the Returns() returns whatever string is input to MyMethod.

Is this possible?

When I try the following, I get System.Reflection.TargetParameterCountException: Parameter count mismatch.

mockObject.Setup( a => a.MyObject.MyMethod( It.IsAny<string>() ).MyProperty ).Returns( (string s) => s );
like image 899
SFun28 Avatar asked Sep 03 '26 01:09

SFun28


1 Answers

How about something like this:

mockObject.Setup( a => a.MyObject.MyMethod( It.IsAny<string>() ) )
    .Returns( (string s) => 
         {
             var mockReturnedObject = new Mock<Returned>();
             mockReturnedObject.Setup(o => o.MyProperty).Returns(s);
             return mockReturnedObject.Object;
         } );

Or, if your "returned object" is just a POCO:

mockObject.Setup( a => a.MyObject.MyMethod( It.IsAny<string>() ) )
    .Returns( (string s) => new Returned {MyProperty = s} );
like image 122
StriplingWarrior Avatar answered Sep 05 '26 16:09

StriplingWarrior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!