Как использовать Moq при издевательстве над сервисом? - PullRequest
0 голосов
/ 17 января 2020

Здравствуйте, я новичок в Moq, и я пытаюсь понять, как moq мои репозитории и проверить мои бизнес логи c из моего сервиса. Я использую шаблон GenericRepository, и я создал метод для инициализации моего root агрегата. Теперь я хотел бы знать, как бы я протестировал все методы сервиса:

public class File
{
   public int Id;
   public string Name;
}

public class IGenericRepository
{
     public IEnumerable<File> GetAllAsync(int take=0,int skip=0,string includeProperties="");
     public bool AddAsync(File file);
     // update,delete,getbyid ,save...etc ,  for brevity just 2 methods
}

public class MyService
{
   private IGenericRepository<File> repo;
   publiC MyService(IGenericRepository<File> repo)
   {
      this.repo=repo;
   }

   public Task<IEnumberable<File>> GetAllAsync(int take,int skip,string includeProperties)
   {
          return this.repo.GetAllAsync(take,skip,includeProperties);
   }
   public async Task AddAsync(File file)
   {
         await this.repo.AddAsync(file);
   }
}

Теперь, имея сервис и репозиторий, я хочу знать, как тестировать состояние репозитория после операций. Например, я хочу посмотреть, возвращает ли мой GetAllAsync другой результат после того, как я позвонил AddAsync:

public class MoqTests
{
   IEnumerable<File> GetFilesFromJson()=>.....;
   [Testcase(3,"test.txt")]
   public async Task CanAddFileAsync(int fileId,string fileName)
   {
      var file=new File(fileId,fileName);
      var files=GetFilesFromJson(); //getting the initial state of the `database`;
      var fileReo=new Mock<IGenericRepository<File>>();
      fileRepo.Setup(x=>x.GetAsync(default,default,default)).ReturnsAsync(y=>{
           //how can i initialize the repo with files
           //how can i get my hands in this lambda on all arguments of `GetAsync`
      });
      //fileRepo.Setup(x=>x.AddAsync()).ReturnsAsync<bool>(...);
      var service=new MyService(fileRepo);

   }
}

В приведенном выше модульном тесте мой вопрос имеет два аспекта:

1. How can i initialize my repository mock with the dataset provided by my unit test method.
2. How can i get my hands in the `ReturnsAsync` method on the arguments provided in the `Setup` `GetAsyncMethod`?

Если в моем Setup пи использовать: repo.Setup(r=> r.Method(arg1,arg2)).ReturnsAsync((arg1,arg2)=>...)

В приведенном выше случае вы можете видеть, что я предоставляю 3 аргумента для моего GetAllAsync: take,skip,includeProperties. Я хочу взять их и проверить логи c в делегате ReturnsAsync:

...ReturnsAsync((take,skip,includeProperties)=>....);
...