简体   繁体   English

Moq 无法实例化包含 lambda 表达式的服务

[英]Moq cannot instantiate service that includes lambda expression

I want to mock the following method with Moq :我想用Moq模拟以下方法:

T GetOne(Expression<Func<T, bool>> expression);

which is called in the following method:在以下方法中调用:

public GetTCNotifyFCResponse GetTCNotifyFC(string operationNumber)
        {
            var response = new GetTCNotifyFCResponse { IsValid = false };

            try
            {
                var tcAbstract = _tcAbstractRepository
                    .GetOne(x => x.Operation.OperationNumber == operationNumber);

                if (tcAbstract == null)
                {
                    response.ErrorMessage = Localization.GetText(WORKFLOW_DONT_STARED);
                    return response;
                }
                [...]

The test code is:测试代码为:

var mockAbstractRep = new Mock<ITCAbstractRepository>();
            mockAbstractRep
                .Setup(s => s.GetOne(x => x.Operation.OperationNumber == operationNumber))
                .Returns(entity);

but when running it I get a null "tcAbstract" result... "operationNumber" and "entity" variables are filled before and have not been included here for simplicity.但是当运行它时,我得到一个空的“tcAbstract”结果......“operationNumber”和“entity”变量之前已经填充,为了简单起见,这里没有包含。

What am I doing wrong?我究竟做错了什么?

Try this and see if it helps试试这个,看看它是否有帮助

var mockAbstractRep = new Mock<ITCAbstractRepository>();
mockAbstractRep
    .Setup(s => s.GetOne(It.IsAny<Expression<Func<EntityType, bool>>>()))
    .Returns(entity);

replace EntityType with the type that your method requiresEntityType替换为您的方法所需的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM