Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq - mocking LINQ When & FirstOrDefault

I have the following code and I am trying to mock it, but my unit test fails.

Code:

await _someDataRepository.GetSomeDataAsync(false)
                         .Where(r => r.Code == statusCode)
                         .FirstOrDefault();

Mock:

Mock<SomeDataRepository> _someDataRepositoryMock = new Mock<SomeDataRepository>();

_someDataRepositoryMock.Setup(s => s.GetSomeDataAsync(It.IsAny<bool>()))
                       .Returns<List<Domain.Student.Entities.SectionRegistrationStatusItem>>(
                           i => Task.FromResult(
                               i.Where(sr => sr.Code == It.IsAny<string>())
                           )
                       );

How would I mock chained statements?

like image 982
Maharaj Avatar asked Oct 31 '22 13:10

Maharaj


1 Answers

As mentioend in the comments, you can't mock Where and/or FirstOrDefault. You'd mock _someDataRepository.GetSomeDataAsync(false) and let Where work on the data that've return from GetSomeDataAsync.

Unfortunately I haven't tested this code, but it might give you some inspiration:

_someDataRepositoryMock.Setup(s => s.GetSomeDataAsync(It.IsAny<bool>()))
                       .Returns(Task.FromResult(Your data here, i.e. List<Domain.Student.Entities.SectionRegistrationStatusItem>));

Or if you are using Moq 4.2 or later

_someDataRepositoryMock.Setup(s => s.GetSomeDataAsync(It.IsAny<bool>()))
                       .ReturnAsync(Your data here, i.e.  List<Domain.Student.Entities.SectionRegistrationStatusItem>);
like image 69
iikkoo Avatar answered Nov 15 '22 04:11

iikkoo