A test double replaces a real dependency with a simplified implementation, letting a component run against controlled data during unit testing. A controller can depend on IDataSource instead of creating or querying its data directly. section 6.3.5
A practical isolation sequence is:
- Define an interface for the dependency, such as IDataSource with a Products property. section 6.3.5
- Make the controller use that interface through a replaceable dataSource property. section 6.3.5
- Implement a fake that accepts test data, assign it to the controller, and assert the resulting view model. section 6.3.5
Controlled controller data
FakeDataSource stores an array containing P1, P2, and P3 products. The test assigns it to HomeController, invokes Index, and checks the returned model without using the production ProductDataSource. section 6.3.5
Listing 6.14 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;
namespace SimpleApp.Tests {
public class HomeControllerTests {
[Fact]
public void IndexActionModelIsComplete() {
// Arrange
var controller = new HomeController();
Product[] products = new Product[] {
new Product { Name = "Kayak", Price = 275M },
new Product { Name = "Lifejacket", Price = 48.95M}
};
// Act
var model = (controller.Index() as ViewResult)?.ViewData.Model
as IEnumerable<Product>;
// Assert
Assert.Equal(products, model,
Comparer.Get<Product>((p1, p2) => p1?.Name == p2?.Name
&& p1?.Price == p2?.Price));
}
}
}
Browse the controller test pattern that arranges controlled products, invokes the action, and compares the resulting model. section 6.3.5





