Mocking replaces a dependency with a configurable test double. In ASP.NET Core unit tests, Moq can implement an interface without a handwritten fake, return controlled data, and record interactions for later verification. section 6.3.7 section 7.1.1
A typical Moq-based test proceeds as follows:
- Create Mock<T> for the dependency interface, such as IDataSource or IStoreRepository. section 6.3.7
- Configure members with Setup or SetupGet and Returns, supplying known products or queryable repository data. section 6.3.7 section 8.1.4
- Inject mock.Object into the controller under test. section 6.3.7
- Verify interactions with Verify or VerifyGet, using Times.Once or Times.Never to enforce required call counts. section 6.3.7 section 9.3.5
Testing category counts and checkout rules
A controller test configures an IStoreRepository mock with products in Cat1, Cat2, and Cat3, calls Index for each category, and checks the resulting totals. OrderController tests use an IOrderRepository mock to prove that an empty cart or invalid shipping details neither saves an order nor redirects, while a valid cart saves exactly once and redirects to Completed. section 8.1.4 section 9.3.5
Listing 6.20 Creating a mock object in the HomeControllerTests.cs file in the SimpleApp.Tests folder
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using SimpleApp.Controllers;
using SimpleApp.Models;
using Xunit;
using Moq;
namespace SimpleApp.Tests {
public class HomeControllerTests {
//class FakeDataSource : IDataSource {
// public FakeDataSource(Product[] data) => Products = data;
// public IEnumerable<Product> Products { get; set; }
//}
[Fact]
public void IndexActionModelIsComplete() {
// Arrange
Product[] testData = new Product[] {
new Product { Name = "P1", Price = 75.10M },
new Product { Name = "P2", Price = 120M },
new Product { Name = "P3", Price = 110M }
};
var mock = new Mock<IDataSource>();
mock.SetupGet(m => m.Products).Returns(testData);
var controller = new HomeController();
controller.dataSource = mock.Object;
// Act
var model = (controller.Index() as ViewResult)?.ViewData.Model
as IEnumerable<Product>;
// Assert
Assert.Equal(testData, model,
Comparer.Get<Product>((p1, p2) => p1?.Name == p2?.Name
&& p1?.Price == p2?.Price));
mock.VerifyGet(m => m.Products, Times.Once);
}
}
}
Use the complete test listing to see test data construction, Mock<IDataSource>, property setup, controller injection, and interaction verification together. section 6.3.7




















