sunil
sunil

Reputation: 5168

Moq Setup returning null

I set up my mock object using Moq like this:

var accountRepositoryMock = new Mock<IGenericRepository<Account>>();
accountRepositoryMock.Setup(r => r.SingleOrDefault(a => a.AccountId == It.IsAny<long>())).Returns(new Account { AccountId = 99999999, Valid = true });

var unitOfWorkMock = new Mock<IUnitOfWork>();
unitOfWorkMock.SetupGet(unitofwork => unitofwork.AccountRepository).Returns(accountRepositoryMock.Object);

Then I pass it to my service like this:

 IQuickPayService quickPayService = new QuickPayService(unitOfWorkMock.Object);
 Account account = quickPayService.ValidateAccount(accountId);

When I do this in my client code, I am getting account as null

public class QuickPayService : IQuickPayService
{
   public QuickPayService(IUnitOfWork unitOfWork)
   {
        _unitOfWork = unitOfWork;
   } 

   public AccountStatus ValidateAccount(long accountId)
   {
        var account;
        using (_unitOfWork)
        {
           account = _unitOfWork.AccountRepository.SingleOrDefault(acc => acc.AccountId == 99999999);

        }
        return account;
   }

}

Any ideas on what I am doing wrong?

Upvotes: 2

Views: 3051

Answers (1)

TrueWill
TrueWill

Reputation: 25563

Assuming that your interface is declared similarly to the following:

public interface IGenericRepository<T>
{
    T SingleOrDefault(Func<T, bool> predicate);
}

Specifying a delegate in Setup won't work. See Issue 300: Mocking Method with Delegate as Parameter. I get a NotSupportedException when I tried it.

Instead, try this:

accountRepositoryMock.Setup(r => r.SingleOrDefault(It.IsAny<Func<Account, bool>>()))
    .Returns(new Account { AccountId = 99999999, Valid = true });

There's a more detailed example at Moq framework Func<T,T>

Upvotes: 2

Related Questions