Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup Mock for generic function with generic Lambda using Moq It.IsAny

Tags:

c#

mocking

moq

I am trying to mock this interface:

public interface IManager
{
    TVal GetOrAdd<TVal, TArg>(string key, Func<TArg, TVal> valueFactory, TArg valueFactoryArg) where TVal : class;
}

And i am having isuse to mock the lambda expression.

var _menagerMock = new Mock<IManager>();
_menagerMock.Setup(x => x.GetOrAdd<string, Tuple<int>>("stringValue",
            It.IsAny<Func<Tuple<int>,string>>, It.IsAny<Tuple<int>>);

the It.IsAny< Func,string>> is not passing compilation, and the error is: Expected a method with 'string IsAny(Tuple)' signature.

Is it possible to mock this kind of function?

like image 732
Matan Shidlov Avatar asked Sep 29 '22 01:09

Matan Shidlov


1 Answers

Try:

        var _menagerMock = new Mock<IManager>();
        _menagerMock.Setup(x => x.GetOrAdd("stringValue",
            It.IsAny<Func<Tuple<int>, string>>(), It.IsAny<Tuple<int>>()));

Edit: As an aside, It.IsAny() is not a best practice for testing. You should be setting up explicit values instead of relying on It.IsAny(). If you're not really sure of the inputs in your tests, how can you be sure that you're getting valid output?

like image 152
C Bauer Avatar answered Oct 03 '22 02:10

C Bauer