Moq-Setup fails when using myLambda() instead of myLambda.Invoke() on It.IsAny<>-MethodGroup

强颜欢笑 提交于 2021-01-28 05:22:36

问题


I use a Util-Method that is an Extension-method delaying It.*-calls until the Setup (using the result of an It.*-call stored in a variable doesn't seem to work).

However, I noticed that when I call the Func<string> message with message(), the Setup will not work properly. When using message.Invoke(), it works just as I expect.

As far as I understand, message() should be syntactic sugar for message.Invoke(), but then why do they behave differently?


I do believe that has something to do with the Moq-Framework, that's why I tagged this moq. Something like Func<string> f = ()=>"test"; f(); returns a string. Moq does lots of magic with It.*, Mock<> and so on, maybe I interfered with it somehow.


Following example:

public interface ILog 
{
    void Debug(string message, Exception exception = null);
}

public class LogUtils
{
    public static void Debug(this Mock<ILog> mock, string message, Exception exception = null)
    {
        mock.Debug(() => message, () => exception);
    }

    public static void Debug(this Mock<ILog> mock, Func<string> message, Func<Exception> exception)
    {
        // NOT working line
        mock.Setup(logger => logger.Debug(message(), exception()));

        // Working line
        mock.Setup(logger => logger.Debug(message.Invoke(), exception.Invoke()));
    }
}


// Test Method
public void TestMethod()
{
    Mock<ILog> logger = new Mock<ILog>(MockBehavior.Strict);

    // Setup logger to accept any input by using It.IsAny<>-MethodGroup
    logger.Debug(It.IsAny<string>, It.IsAny<Exception>);

    // Fails with no corresponding setup
    logger.Object.Debug("Test");
}

来源:https://stackoverflow.com/questions/46973555/moq-setup-fails-when-using-mylambda-instead-of-mylambda-invoke-on-it-isany

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!