0

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.

Johnny
  • 8,939
  • 2
  • 28
  • 33
tahasozgen2
  • 148
  • 1
  • 1
  • 9

1 Answers1

1

It should be possible, try this:

_workerRepositoryMock
    .Setup(m => m.ReadWorkerList(It.Is<AcademicTitle>(v => v != AcademicTitle.Empty)))
    .Returns((AcademicTitle v) => workerList.Where(p => p.Title == v));
Johnny
  • 8,939
  • 2
  • 28
  • 33
  • There are three functions that sharing the same name with the function in *ReadWorkerList* and the error is "no overload for method 'IsAny' takes 1 argument" – tahasozgen2 Jul 26 '19 at 07:48
  • 1
    It should be _workerRepositoryMock.Setup(m => ReadWorkerList(It.Is(v => v != AcademicTitle.Empty))) .Returns((AcademicTitle v) => calisanListe.Where(p => p.Title == v)); Please note that It.Is used instead of It.IsAny. – tahasozgen2 Jul 26 '19 at 07:56