ASP.NET Core Web API Interview Question #151
What is unit testing in ASP.NET Core Web API?
Testing, HttpClient, Integration Testing, Background Services & Deployment Senior Advanced
Quick Interview Answer
Unit testing verifies a small unit of application behavior in isolation, such as a service method, validator, mapper, or controller decision. Dependencies are normally replaced with test doubles so the test focuses on one behavior.
Detailed Explanation
Unit testing verifies a small unit of application behavior in isolation, such as a service method, validator, mapper, or controller decision. Dependencies are normally replaced with test doubles so the test focuses on one behavior.
Good unit tests are fast, deterministic, and focused on observable outcomes rather than internal implementation details.
Code Example
[Fact]
public async Task Get_ReturnsProduct_WhenFound()
{
var service = new Mock<IProductService>();
service.Setup(x => x.GetAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new ProductResponse { Id = 1, Name = "Phone" });
var controller = new ProductsController(service.Object);
var result = await controller.Get(1, CancellationToken.None);
Assert.NotNull(result.Value);
}