liveBook · Manning

Mocking

As explained in Pro ASP.NET Core 7, Tenth Edition

A mock object is a test double that imitates a dependency and can provide controlled behavior or interaction verification.

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

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Works through interface setup, dependency injection, returned data, and call-count verification, but defers Moq's broader feature set.
Examples
Demonstrates mocked products, category-specific pagination counts, empty-cart rejection, invalid shipping details, and successful order submission.
What it assumes
Assumes interfaces, controllers, dependency injection, and unit-test assertions while teaching Moq setup and verification from usage.
What you can do after
Apply it via Moq to configure dependencies, inject them into controllers, and verify behavior and interaction counts.
How it connects
Connects unit testing with dependency injection, interfaces, controllers, model binding, repositories, and assertions.

Also explained in

Compare how 21 books explain mocking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.