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?
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>);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With