I want to test a function that returns a list of complex type. So I need moq to simulate this function. The function is
IEnumerable (Worker> ReadWorkerList(AcademicTitle title);
During the setup section of the moq, I have created a artifical Worker list (code-1) and I cannot instruct moq to return the subset of worker list which satisfies the AcademicTitle criteria in the parameter. (code-2)
I have read the urls below and I cannot find solution.
Return Subset of List that Matches Condition Moq Return using Where() Mock object returning a list of mocks with Moq MOQ C# QUERIES It.IsAny returning a List Overloaded return values in MOQ
Definition of Worker:
public class Worker
{
public string Name { get; set; }
public string Surname { get; set; }
public AcademicTitle Title { get; set; }
}
//Moq implementation: (code-1)
internal static Mock<IWorkerRepository> GetIWorkerRepository ()
{
try
{
if (_workerRepositoryMock == null)
{
//artifical worker list
List<Worker> workerList = new List<Worker>() {
new Worker("name1", "surname1",AcademicTitle.Doctor),
new Worker("name2", "surname2",AcademicTitle.Empty),
new Worker("name3", "surname3",AcademicTitle.AssociateProfessor),
new Worker("name4", "surname4",AcademicTitle.Professor),
};
_workerRepositoryMock = new Mock<IWorkerRepository>();
_workerRepositoryMock.Setup(m => m.ReadWorkerList(It.IsAny<AcademicTitle>())).Returns(new List<Worker>());
//Code -2
_workerRepositoryMock.Setup(m => m.ReadWorkerList(It.Is<AcademicTitle>(v=>v != AcademicTitle.Empty))).Returns(workerList.Where(p=>p.Title == v));
}
return _workerRepositoryMock;
}catch (Exception hata)
{
throw hata;
}
}
Expected result is, when I call ReadWorkerList function with a specific AcademicTitle parameter, let's say Professor, only a list that contains name4 should be returned.