I'm new to Moq. I'm trying to setup my Repository to return a value when called:
My test method:
_userServiceMock.Setup(m => m.GetUserIDByUserName(It.IsAny<string>())).Returns(2);
_bidRepositoryMock.Setup(m => m.Match(It.IsAny<Func<IQueryable<Bid>, object>>(),
It.IsAny<Expression<Func<Bid, object>>[]>())).Returns(new Bid{UserId = 2});
var service = SetupService();
var result = service.GetOwnBid(1, "testuser");
The userServiceMock returns 2 just as it should, but the bidRepositoryMock returns null.
The Method I'm unit testing looks like this:
var bid = _bidRepository.Match(userBid => userBid.SingleOrDefault(b => b.ID == id),
b => b.UserProfile,
b => b.Task.UserProfile);
and the BidRepository Method Match Looks like this:
TResult Match<TResult>(Func<IQueryable<T>, TResult> query, params Expression<Func<T, object>>[] includes);
Try to change this code from It.IsAny<Func<IQueryable<Bid>, object>>()
to It.IsAny<Func<IQueryable<Bid>, Bid>>()
_bidRepositoryMock.Setup(m => m.Match(It.IsAny<Func<IQueryable<Bid>, Bid>>(),
It.IsAny<Expression<Func<Bid, object>>[]>())).Returns(new Bid{UserId = 2});
Because you method returns the TResult
type in your query it will be the Bid
type.