Unit Testing Your API Controllers
🪛 Unit Testing Your API Controllers
Install xUnit and Moq:
dotnet add package xunit
dotnet add package Moq
Example test:
[Fact]
public void GetAll_ReturnsAllProducts()
{
var mockRepo = new Mock<IProductRepository>();
mockRepo.Setup(repo => repo.GetAll()).Returns(new List<Product> {
new() { Id = 1, Name = "Test", Price = 9.99M }
});
var controller = new ProductsController(mockRepo.Object);
var result = controller.GetAll();
var okResult = Assert.IsType<OkObjectResult>(result.Result);
var products = Assert.IsType<List<Product>>(okResult.Value);
Assert.Single(products);
}