ASP.NET Core MVC Interview Question #151
What is unit testing in ASP.NET Core MVC?
Testing, AJAX/JavaScript Integration, Localization & Advanced MVC Senior Advanced
Quick Interview Answer
Unit testing verifies a small unit of application behavior in isolation, such as a controller action or service method. Dependencies are normally replaced with test doubles so the test focuses on the unit's own decisions rather than databases, networks, or the full ASP.NET Core pipeline.
Detailed Explanation
Unit testing verifies a small unit of application behavior in isolation, such as a controller action or service method. Dependencies are normally replaced with test doubles so the test focuses on the unit's own decisions rather than databases, networks, or the full ASP.NET Core pipeline.
For MVC applications, the most valuable unit tests usually target business and application services. Controller unit tests are useful when actions contain meaningful HTTP-flow decisions such as returning NotFound, redisplaying an invalid model, or redirecting after success.
Code Example
[Fact]
public async Task Details_ReturnsNotFound_WhenMissing()
{
var service = new Mock<IProductService>();
service.Setup(x => x.GetAsync(10, default))
.ReturnsAsync((ProductViewModel?)null);
var controller = new ProductsController(service.Object);
var result = await controller.Details(10, default);
Assert.IsType<NotFoundResult>(result);
}