Это моя служба;
Код: Выделить всё
public async Task AddProductAsync(Product product)
{
_logger.LogInformation("Adding product: {@Product}", product);
await _context.Products.AddAsync(product);
_logger.LogInformation("Before SaveChangesAsync");
await _context.SaveChangesAsync();
_logger.LogInformation("After SaveChangesAsync");
_logger.LogInformation("Product added successfully with ID: {ProductId}", product.Id);
}
< /code>
Вот код контроллера для метода post < /p>
[HttpPost]
public async Task PostProduct([FromBody] Product product)
{
// Log the incoming product data
_logger.LogInformation("Adding a new product: {@Product}", product);
// ✅ Automatic Model Validation
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // Returns validation errors automatically
}
// Check for duplicate products by ID
var existingProduct = await _repository.GetProductByIdAsync(product.Id);
Console.WriteLine("Output is here" + existingProduct);
if (existingProduct != null)
{
return new ConflictObjectResult(new { message = "A product with the same ID already exists." });
}
// Add the product to the repository
await _repository.AddProductAsync(product);
Console.WriteLine("The product is >>" + product);
// Return the created product with a 201 status code and location header
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
< /code>
Также я реализовал модульный тестовый пример для Post Method: < /p>
[Test]
public async Task AddProduct_ValidProduct()
{
// Arrange
var newProduct = new Product { Id = 3, Name = "Chocolate", Price = "15", Quantity = 8 };
_mockRepository.Setup(repo => repo.AddProductAsync(It.IsAny()))
.Callback(p => _products.Add(p)) // Actually add it to the list
.Returns(Task.CompletedTask);
// Act
var result = await _controller.PostProduct(newProduct);
Console.WriteLine("What is newProduct" + newProduct);
// Assert: Check response
Assert.That(result.Result, Is.InstanceOf(), "Expected CreatedAtActionResult");
var createdResult = result.Result as CreatedAtActionResult;
Assert.That(createdResult?.Value, Is.Not.Null, "Expected non-null created product");
var addedProduct = createdResult?.Value as Product;
Assert.That(addedProduct?.Id, Is.EqualTo(3), "Expected product ID 3");
Assert.That(_products.Any(p => p.Id == 3 && p.Name == "Chocolate"), Is.True,
"Product was actually added to the repository.");
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... -and-nunit