public async Task ThatDoesNotExistItShouldThrow()
        {
            // Arrange
            var context     = LivestockDbContextFactory.Create(_loggerFactory);
            var service     = SetUpService(context);
            var transaction = new WeightTransaction
            {
                Id              = 999,
                AnimalId        = TestConstants.AnimalId1,
                TransactionDate = TestConstants.DefaultDate,
                Weight          = 120
            };

            // Act
            var exception = await Assert.ThrowsAsync <EntityNotFoundException <WeightTransaction> >(
                async() =>
            {
                await service.UpdateAsync(transaction, CancellationToken.None)
                .ConfigureAwait(true);
            })
                            .ConfigureAwait(true);

            // Assert
            Assert.NotNull(exception);
            Assert.Equal($"{nameof(WeightTransaction)} with id {transaction.Id} not found.", exception.Message);
        }
        public async Task <IActionResult> UpdateAsync(long id, UpdateWeightTransactionViewModel model)
        {
            Logger.LogInformation("Requesting the update of weight transaction: {@Transaction} for animal {@AnimalId}...", model, model.AnimalId);

            if (id != model.Id)
            {
                ModelState.AddModelError(nameof(model.Id), "The id in the body does match the id in the route.");
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var transaction = new WeightTransaction
            {
                Id              = id,
                AnimalId        = model.AnimalId,
                TransactionDate = model.TransactionDate,
                Weight          = model.Weight
            };

            transaction = await _weightTransactionCrudService.UpdateAsync(transaction, RequestAbortToken).ConfigureAwait(false);

            return(Ok(transaction));
        }
 private void ValidateAddAsyncParameters(WeightTransaction item)
 {
     if (!_context.Animals.Any(animal => animal.Id == item.AnimalId))
     {
         throw new TransactionRequiresAnimalException(item.AnimalId);
     }
 }
예제 #4
0
        /// <summary>
        /// Sets the values that are allowed to be changed.
        /// </summary>
        /// <param name="transaction">
        /// The transaction with the updated values.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// When an attempt is made to move the transaction to another animal.
        /// </exception>
        public void SetValues(WeightTransaction transaction)
        {
            if (transaction.AnimalId != AnimalId)
            {
                throw new InvalidOperationException("Cannot move a transaction to a different animal.");
            }

            TransactionDate = transaction.TransactionDate;
            Weight          = transaction.Weight;
        }
        /// <inheritdoc/>
        public async Task <WeightTransaction> AddAsync(WeightTransaction item, CancellationToken cancellationToken)
        {
            _logger.LogInformation("Adding a new weight transaction for animal ({@AnimalId})", item.AnimalId);

            ValidateAddAsyncParameters(item);

            var transaction = new WeightTransactionModel
            {
                AnimalId        = item.AnimalId,
                TransactionDate = item.TransactionDate,
                Weight          = item.Weight
            };

            var changes = _context.WeightTransactions.Add(transaction);

            await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            return(changes.Entity.MapToWeightTransaction());
        }
        public async Task <IActionResult> CreateAsync(CreateWeightTransactionViewModel model)
        {
            Logger.LogInformation("Requesting the creation of weight transaction: {@Transaction} for animal {@AnimalId}...", model, model.AnimalId);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var transaction = new WeightTransaction
            {
                AnimalId        = model.AnimalId,
                TransactionDate = model.TransactionDate,
                Weight          = model.Weight
            };

            transaction = await _weightTransactionCrudService.AddAsync(transaction, RequestAbortToken).ConfigureAwait(false);

            return(Ok(transaction));
        }
        /// <inheritdoc/>
        /// <exception cref="InvalidOperationException">
        /// When an attempt is made to move the transaction to a different animal.
        /// </exception>
        /// <exception cref="EntityNotFoundException{T}">
        /// When an attempt is made to update a transaction that cannot be found.
        /// </exception>
        public async Task <WeightTransaction> UpdateAsync(WeightTransaction item, CancellationToken cancellationToken)
        {
            _logger.LogInformation("Updating the weight transaction ({@Id}) for animal ({@AnimalId})", item.Id, item.AnimalId);

            var transaction = await _context.WeightTransactions
                              .FindAsync(new object[] { item.Id }, cancellationToken)
                              .ConfigureAwait(false);

            if (transaction == null)
            {
                throw new EntityNotFoundException <WeightTransaction>(item.Id);
            }

            transaction.SetValues(item);

            var changes = _context.Update(transaction);
            await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            return(changes.Entity.MapToWeightTransaction());
        }
        public async Task ForAnAnimalThatDoesNotExistItShouldThrow()
        {
            // Arrange
            var context = LivestockDbContextFactory.Create(_loggerFactory);
            var service = new WeightTransactionCrudService(_logger, context);

            // Act
            var transaction = new WeightTransaction
            {
                AnimalId        = TestConstants.AnimalId1,
                TransactionDate = TestConstants.DefaultDate,
                Weight          = 100
            };
            var exception = await Assert.ThrowsAsync <TransactionRequiresAnimalException>(async() => await service.AddAsync(transaction, CancellationToken.None));

            // Assert
            Assert.NotNull(exception);
            Assert.Equal(TestConstants.AnimalId1, exception.AnimalId);
            Assert.Equal("The animal for this transaction could not be found.", exception.Message);
        }
        public async Task ThatDoesNotExistItShouldAddItToTheDatabase()
        {
            // Arrange
            var context = LivestockDbContextFactory.Create(_loggerFactory);

            context.SeedTestAnimal(TestConstants.AnimalId1);
            context.SaveChanges();
            var service = new WeightTransactionCrudService(_logger, context);

            // Act
            var transaction = new WeightTransaction
            {
                AnimalId        = TestConstants.AnimalId1,
                TransactionDate = TestConstants.DefaultDate,
                Weight          = 100
            };
            await service.AddAsync(transaction, CancellationToken.None);

            // Assert
            Assert.Equal(1, context.WeightTransactions.Count());
        }