Пример #1
0
        public WorkNoteService BuildService()
        {
            Mock <IGenericRepository <WorkNote> > mockRepository = new Mock <IGenericRepository <WorkNote> >();

            mockRepository
            .Setup(inst => inst.All)
            .Returns(() => new TestAsyncEnumerable <WorkNote>(_testData));
            mockRepository
            .Setup(inst => inst.GetByIdAsync(It.IsAny <int>()))
            .ReturnsAsync((int id) => _testData.Where(item => item.Id == id).SingleOrDefault());
            mockRepository
            .Setup(inst => inst.CreateAsync(It.IsAny <WorkNote>()))
            .Callback((WorkNote newWorkNote) =>
            {
                newWorkNote.Id          = _nextId++;
                newWorkNote.CreatedDate = DateTime.Now;
                _testData.Add(newWorkNote);
            });
            mockRepository
            .Setup(inst => inst.UpdateAsync(It.IsAny <WorkNote>()))
            .Callback((WorkNote entry) =>
            {
                var match = _testData.FirstOrDefault(item => item.Id == entry.Id);
                if (match == null)
                {
                    throw new NotFoundException($"Item with id={entry.Id} not found.");
                }

                match.Title   = entry.Title;
                match.Content = entry.Content;
            });
            mockRepository
            .Setup(inst => inst.DeleteAsync(It.IsAny <int>()))
            .Callback((int id) =>
            {
                var match = _testData.FirstOrDefault(item => item.Id == id);
                if (match == null)
                {
                    throw new NotFoundException($"Item with id={id} not found.");
                }

                _testData = _testData.Where(item => item.Id != id).ToList();
            });

            WorkNoteService service = new WorkNoteService(mockRepository.Object, AutoMapperProfile.MapperFactory());

            return(service);
        }