Assert the result. Example: public class ProductsControllerTests { [Fact] public void Get_ReturnsOkResult_WithProducts() { // Arrange var mockService = new Mock<IProductService>(); mockService.Setup(s => s.GetAll()).Returns(new List<Product> { new Product { Id = 1, Name = "Laptop" } }); var controller = new ProductsController(mockService.Object); Follow : // Act var result = controller.Get(); // Assert var okResult = Assert.IsType<OkObjectResult>(result); var products = Assert.IsType<List<Product>>(okResult.Value); Assert.Single(products); } } ✅ Key: Mock all dependencies so controller is tested in isolation. 2⃣ How to Mock DbContext for Testing?
EF Core allows using InMemoryDatabase or mocking DbSet<T> to avoid hitting a real
database.
Example with InMemoryDatabase:
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase(databaseName: "TestDb")
.Options;
using var context = new AppDbContext(options);
context.Products.Add(new Product { Id = 1, Name = "Laptop" });
context.SaveChanges();
// Act
var service = new ProductService(context);
var products = service.GetAll();
// Assert
Assert.Single(products);
Example with Moq (for advanced mocking):
Follow :
var mockSet = new Mock<DbSet<Product>>();
var mockContext = new Mock<AppDbContext>();
mockContext.Setup(c => c.Products).Returns(mockSet.Object);
3⃣ What is Integration Testing in ASP.NET Core?
Integration tests test the application as a whole, including middleware, routing,
controllers, and database.
- Ensures all parts work together.
- Usually uses WebApplicationFactory for hosting the app in-memory.
Example:
public class ProductsApiTests :
IClassFixture<WebApplicationFactory<Program>>
private readonly HttpClient _client;
public ProductsApiTests(WebApplicationFactory<Program> factory)
_client = factory.CreateClient();
[Fact]
public async Task GetProducts_ReturnsOk()
var response = await _client.GetAsync("/api/products");
response.EnsureSuccessStatusCode();
var products = await
response.Content.ReadFromJsonAsync<List<Product>>();
Assert.NotNull(products);
Follow :
✅ Integration tests are slower but catch real runtime issues.
4⃣ How Do You Test Middleware?
Middleware can be tested by invoking it in isolation using RequestDelegate.
Example:
[Fact]
public async Task CustomMiddleware_SetsHeader()
// Arrange
var middleware = new CustomHeaderMiddleware(async
(innerHttpContext) =>
await innerHttpContext.Response.WriteAsync("Hello");
});
var context = new DefaultHttpContext();
// Act
await middleware.InvokeAsync(context);
// Assert
Assert.Equal("MyValue",
context.Response.Headers["X-Custom-Header"]);
✅ Test middleware without starting a real server.
5⃣ How to Use WebApplicationFactory for Testing?
Follow :
WebApplicationFactory<T> spins up your ASP.NET Core app in-memory, perfect for
integration tests or testing minimal APIs.
Example:
var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient();
var response = await client.GetAsync("/api/products");
response.EnsureSuccessStatusCode();
You can override services for testing:
var factory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
builder.ConfigureServices(services =>
services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase("TestDb"));
});
});
6⃣ How to Test Minimal APIs?
Minimal APIs are tested using WebApplicationFactory or TestServer.
Example:
var factory = new WebApplicationFactory<Program>();
var client = factory.CreateClient();
var response = await client.GetAsync("/products");
var products = await
response.Content.ReadFromJsonAsync<List<Product>>();
Follow :
Assert.NotEmpty(products);
7⃣ What Frameworks Are Commonly Used?
- xUnit – Popular, lightweight, supports parallel testing.
- NUnit – Rich assertion library.
- MSTest – Microsoft-supported, integrated in Visual Studio.
Most modern ASP.NET Core projects use xUnit + Moq.
8⃣ How to Use Moq for Mocking Dependencies?
Moq creates fake implementations of interfaces to control behavior during tests.
Example:
var mockRepo = new Mock<IProductRepository>();
mockRepo.Setup(x => x.GetAll()).Returns(new List<Product> { new
Product { Id = 1, Name = "Laptop" } });
var service = new ProductService(mockRepo.Object);
var products = service.GetAll();
Assert.Single(products);
✅ Use .Setup(), .Verify(), and .Returns() to simulate behavior.
9⃣ How to Use InMemoryDatabase for EF Core Testing?
Follow :
EF Core InMemoryDatabase allows quick tests without SQL Server.
Steps: