Luis
Luis

Reputation: 3033

Moq cannot instantiate service that includes lambda expression

I want to mock the following method with 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.

What am I doing wrong?

Upvotes: 1

Views: 78

Answers (1)

Nkosi
Nkosi

Reputation: 247088

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 requires

Upvotes: 1

Related Questions