[{"data":1,"prerenderedAt":106},["ShallowReactive",2],{"qa-\u002Fdotnet\u002Ftesting\u002Fmocking":3},{"page":4,"siblings":93,"blog":103},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":12,"path":20,"questions":21,"questionsCount":84,"related":85,"seo":86,"seoDescription":87,"stem":88,"subtopic":6,"topic":89,"topicSlug":90,"updated":91,"__hash__":92},"qa\u002Fdotnet\u002Ftesting\u002Fmocking.md","Mocking",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md",".NET Core","dotnet",{},true,"\u002Fdotnet\u002Ftesting\u002Fmocking",[22,27,31,35,39,43,47,51,55,60,64,68,72,76,80],{"id":23,"difficulty":24,"q":25,"a":26},"what-is-mocking","easy","What is mocking and why is it used in unit tests?","**Mocking** replaces a real dependency with a controllable substitute that\nrecords calls and returns predetermined values. It isolates the unit under\ntest from slow, unreliable, or side-effecting collaborators.\n\n```csharp\n\u002F\u002F Without mocking — test depends on a live email server:\npublic class OrderService\n{\n    private readonly SmtpEmailSender _emailSender;\n    public OrderService() => _emailSender = new SmtpEmailSender(); \u002F\u002F tight coupling\n\n    public void PlaceOrder(Order order)\n    {\n        \u002F\u002F ... business logic ...\n        _emailSender.Send(order.Email, \"Confirmed!\"); \u002F\u002F hits live SMTP in tests!\n    }\n}\n\n\u002F\u002F With mocking — inject an interface, replace in tests:\npublic class OrderService\n{\n    private readonly IEmailSender _emailSender;\n    public OrderService(IEmailSender emailSender) => _emailSender = emailSender;\n\n    public void PlaceOrder(Order order)\n    {\n        \u002F\u002F ... business logic ...\n        _emailSender.Send(order.Email, \"Confirmed!\");\n    }\n}\n\n\u002F\u002F In the test — Moq creates a fake IEmailSender:\nvar mockEmail = new Mock\u003CIEmailSender>();\nvar service   = new OrderService(mockEmail.Object);\nservice.PlaceOrder(new Order { Email = \"a@b.com\" });\n\n\u002F\u002F Verify the interaction without sending any real email:\nmockEmail.Verify(e => e.Send(\"a@b.com\", \"Confirmed!\"), Times.Once);\n```\n\n**Rule of thumb:** Mock collaborators at the boundary of the unit under test.\nDon't mock things you own and control — mock external dependencies (email,\ndatabase, HTTP, clock) where real execution would slow or break tests.\n",{"id":28,"difficulty":24,"q":29,"a":30},"moq-setup-returns","How do you configure a mock to return a value using Moq?","Moq uses `Setup(...).Returns(...)` to configure what a mock returns when\na method is called with specific (or any) arguments.\n\n```csharp\nusing Moq;\n\nvar mockRepo = new Mock\u003CIProductRepository>();\n\n\u002F\u002F Return a specific value for exact arguments:\nmockRepo.Setup(r => r.GetById(42))\n        .Returns(new Product { Id = 42, Name = \"Widget\" });\n\n\u002F\u002F Return for ANY int argument — It.IsAny\u003CT>():\nmockRepo.Setup(r => r.GetById(It.IsAny\u003Cint>()))\n        .Returns(new Product { Id = 1, Name = \"Fallback\" });\n\n\u002F\u002F Return based on the argument value — It.Is\u003CT>(predicate):\nmockRepo.Setup(r => r.GetById(It.Is\u003Cint>(id => id > 0)))\n        .Returns\u003Cint>(id => new Product { Id = id, Name = $\"Product {id}\" });\n\n\u002F\u002F Return null (for reference types):\nmockRepo.Setup(r => r.GetById(999)).Returns((Product?)null);\n\n\u002F\u002F Throw an exception:\nmockRepo.Setup(r => r.GetById(-1))\n        .Throws\u003CArgumentOutOfRangeException>();\n\n\u002F\u002F Async methods — use ReturnsAsync:\nvar mockAsyncRepo = new Mock\u003CIProductRepository>();\nmockAsyncRepo.Setup(r => r.GetByIdAsync(42))\n             .ReturnsAsync(new Product { Id = 42 });\n\n\u002F\u002F Use the mock:\nvar product = mockRepo.Object.GetById(42); \u002F\u002F returns Widget\n```\n\n**Rule of thumb:** Prefer `It.IsAny\u003CT>()` for stubs where you only care about\nthe return value, and use exact argument matching only when the argument itself\nis what the test is validating.\n",{"id":32,"difficulty":24,"q":33,"a":34},"moq-verify","How do you verify that a method was called on a mock using Moq?","`mock.Verify(...)` asserts that a method was called after the system under\ntest has run. If the expectation is not met, the test fails.\n\n```csharp\nvar mockEmailer = new Mock\u003CIEmailSender>();\nvar service     = new OrderService(mockEmailer.Object);\nservice.PlaceOrder(new Order { Email = \"user@example.com\", Total = 99m });\n\n\u002F\u002F Was it called exactly once with these specific args?\nmockEmailer.Verify(\n    e => e.Send(\"user@example.com\", It.IsAny\u003Cstring>()),\n    Times.Once);\n\n\u002F\u002F Was it called at least once?\nmockEmailer.Verify(e => e.Send(It.IsAny\u003Cstring>(), It.IsAny\u003Cstring>()),\n                   Times.AtLeastOnce);\n\n\u002F\u002F Was it NEVER called? (assert no interaction happened)\nmockEmailer.Verify(\n    e => e.Send(It.IsAny\u003Cstring>(), It.IsAny\u003Cstring>()),\n    Times.Never);\n\n\u002F\u002F Times options:\n\u002F\u002F Times.Once           — exactly 1 call\n\u002F\u002F Times.Never          — 0 calls\n\u002F\u002F Times.Exactly(n)     — exactly n calls\n\u002F\u002F Times.AtLeastOnce    — >= 1 call\n\u002F\u002F Times.AtMost(n)      — \u003C= n calls\n\u002F\u002F Times.Between(n, m, Range.Inclusive)\n\n\u002F\u002F VerifyAll — fails if any Setup was not called (requires explicit setups)\nmockEmailer.VerifyAll();\n\n\u002F\u002F VerifyNoOtherCalls — fails if any unexpected calls were made\nmockEmailer.VerifyNoOtherCalls();\n```\n\n**Rule of thumb:** `Verify` for interactions that are the test's primary\nassertion; `VerifyNoOtherCalls` to lock down that no unexpected side effects\noccurred.\n",{"id":36,"difficulty":14,"q":37,"a":38},"strict-vs-loose-mocks","What is the difference between strict and loose mocks in Moq?","**Loose** (default) mocks return default values for any call without a\n`Setup`. **Strict** mocks throw `MockException` for any call that was not\nexplicitly configured.\n\n```csharp\n\u002F\u002F Loose mock — unconfigured methods return default values silently\nvar looseMock = new Mock\u003CIProductRepository>(); \u002F\u002F MockBehavior.Loose (default)\nlooseMock.Setup(r => r.GetById(1)).Returns(new Product());\n\nvar result = looseMock.Object.GetById(99); \u002F\u002F no setup — returns null (no exception)\nlooseMock.Object.Delete(99);               \u002F\u002F no setup — executes but does nothing\n\n\u002F\u002F Strict mock — any unconfigured call throws\nvar strictMock = new Mock\u003CIProductRepository>(MockBehavior.Strict);\nstrictMock.Setup(r => r.GetById(1)).Returns(new Product());\n\nvar r2 = strictMock.Object.GetById(1); \u002F\u002F OK — configured\n\u002F\u002F strictMock.Object.GetById(99);       \u002F\u002F throws MockException — not configured\n\u002F\u002F strictMock.Object.Delete(99);        \u002F\u002F throws MockException — not configured\n\n\u002F\u002F When strict makes sense:\n\u002F\u002F - You want to catch unexpected calls (no accidental side effects)\n\u002F\u002F - Writing exhaustive interaction tests\n\n\u002F\u002F When loose makes sense:\n\u002F\u002F - You only care about specific interactions\n\u002F\u002F - Setting up all paths in complex objects is noisy and fragile\n\u002F\u002F - The test is state-based (not interaction-based)\n```\n\nMost teams default to loose and use `VerifyNoOtherCalls()` selectively\nwhen they need the strict behaviour without the global rigidity.\n\n**Rule of thumb:** Start with loose mocks. Switch to strict when you are writing\nsecurity- or audit-critical code where unexpected calls are a bug, not a detail.\n",{"id":40,"difficulty":14,"q":41,"a":42},"argument-matchers","What argument matchers does Moq provide and when do you use each?","Argument matchers let you write flexible setups and verifications that match\non conditions rather than exact values.\n\n```csharp\nvar mock = new Mock\u003CIOrderRepository>();\n\n\u002F\u002F It.IsAny\u003CT>() — match any value of that type\nmock.Setup(r => r.Save(It.IsAny\u003COrder>())).Returns(true);\n\n\u002F\u002F It.Is\u003CT>(predicate) — match a value satisfying a condition\nmock.Setup(r => r.Save(It.Is\u003COrder>(o => o.Total > 0 && o.CustomerId != Guid.Empty)))\n    .Returns(true);\n\n\u002F\u002F It.IsNotNull\u003CT>() — any non-null value\nmock.Setup(r => r.Save(It.IsNotNull\u003COrder>())).Returns(true);\n\n\u002F\u002F It.IsIn \u002F It.IsNotIn — value in a set\nmock.Setup(r => r.GetByStatus(It.IsIn(OrderStatus.Pending, OrderStatus.Processing)))\n    .Returns(new List\u003COrder>());\n\n\u002F\u002F It.IsRegex — string matching a pattern\nvar mockLogger = new Mock\u003CILogger\u003COrderService>>();\nmockLogger.Setup(l => l.Log(\n    LogLevel.Error,\n    It.IsAny\u003CEventId>(),\n    It.Is\u003CIt.IsAnyType>((v, t) => v.ToString()!.Contains(\"failed\")),\n    It.IsAny\u003CException>(),\n    It.IsAny\u003CFunc\u003CIt.IsAnyType, Exception?, string>>()));\n\n\u002F\u002F Capture arguments with Callback for later inspection:\nOrder? captured = null;\nmock.Setup(r => r.Save(It.IsAny\u003COrder>()))\n    .Callback\u003COrder>(o => captured = o)\n    .Returns(true);\n```\n\nMixing exact values and matchers in the same `Setup` call requires all arguments\nto use matchers — you cannot mix `It.IsAny\u003CT>()` with a literal in the same call.\n\n**Rule of thumb:** Use exact values when the argument is what you are testing,\n`It.IsAny\u003CT>()` when you just need a return value, and `It.Is\u003CT>(predicate)`\nwhen partial matching is needed.\n",{"id":44,"difficulty":14,"q":45,"a":46},"mock-callbacks","How do you use Callback in Moq to capture or inspect method arguments?","`Callback` lets you run custom code when a mocked method is called — most\ncommonly to capture arguments for later assertions or to simulate side effects.\n\n```csharp\nvar mockRepo = new Mock\u003CIOrderRepository>();\nvar savedOrders = new List\u003COrder>();\n\n\u002F\u002F Capture all saved orders:\nmockRepo.Setup(r => r.Save(It.IsAny\u003COrder>()))\n        .Callback\u003COrder>(order => savedOrders.Add(order))\n        .Returns(true);\n\nvar service = new OrderService(mockRepo.Object);\nservice.PlaceOrder(new Order { Sku = \"X\", Quantity = 2 });\nservice.PlaceOrder(new Order { Sku = \"Y\", Quantity = 1 });\n\n\u002F\u002F Now inspect what was saved:\nAssert.Equal(2, savedOrders.Count);\nAssert.Equal(\"X\", savedOrders[0].Sku);\n\n\u002F\u002F Callback before return (chained):\nmockRepo.Setup(r => r.Save(It.IsAny\u003COrder>()))\n        .Callback\u003COrder>(o => Console.WriteLine($\"Saving {o.Sku}\"))\n        .Returns(true);\n\n\u002F\u002F Simulate a changing return value on successive calls:\nvar callCount = 0;\nmockRepo.Setup(r => r.GetPendingCount())\n        .Callback(() => callCount++)\n        .Returns(() => callCount * 10); \u002F\u002F returns 10 first call, 20 second, etc.\n\n\u002F\u002F Async version:\nmockRepo.Setup(r => r.SaveAsync(It.IsAny\u003COrder>()))\n        .Callback\u003COrder>(o => savedOrders.Add(o))\n        .ReturnsAsync(true);\n```\n\n**Rule of thumb:** Prefer `Verify` over `Callback` for interaction assertions —\nCallback is best when you need to capture a value or inspect complex argument\nstate that `Verify` cannot express inline.\n",{"id":48,"difficulty":14,"q":49,"a":50},"mock-sequences","How do you set up a mock to return different values on successive calls?","Moq supports chaining `.Returns()` calls (via `SetupSequence`) or using a\nqueue pattern to configure different return values per invocation.\n\n```csharp\nvar mockRetry = new Mock\u003CIHttpClient>();\n\n\u002F\u002F SetupSequence — first call returns null, second returns a value\nmockRetry.SetupSequence(c => c.GetAsync(\"\u002Fapi\u002Fdata\"))\n         .Returns(Task.FromResult((string?)null))  \u002F\u002F 1st call\n         .Returns(Task.FromResult(\"{ \\\"ok\\\": true }\")) \u002F\u002F 2nd call\n         .Throws\u003CHttpRequestException>();            \u002F\u002F 3rd call → exception\n\n\u002F\u002F Use it to test retry logic:\nvar client  = new ResilienceClient(mockRetry.Object, maxRetries: 2);\nvar result  = await client.GetWithRetryAsync(\"\u002Fapi\u002Fdata\");\nAssert.Equal(\"{ \\\"ok\\\": true }\", result);\n\n\u002F\u002F Queue pattern using a list for more flexibility:\nvar responses = new Queue\u003Cint>(new[] { 503, 503, 200 });\nvar mockHttp  = new Mock\u003CIHttpClient>();\nmockHttp.Setup(c => c.GetStatusCodeAsync(It.IsAny\u003Cstring>()))\n        .ReturnsAsync(() => responses.Dequeue());\n\n\u002F\u002F Returns for a property that changes after a method call:\nvar mockContext = new Mock\u003CIAppContext>();\nvar isConnected = false;\nmockContext.Setup(c => c.Connect()).Callback(() => isConnected = true);\nmockContext.Setup(c => c.IsConnected).Returns(() => isConnected);\n```\n\n**Rule of thumb:** Use `SetupSequence` for testing retry\u002Fresilience logic where\ncall order matters. For state that changes in response to side effects, `Callback`\n+ a captured variable is cleaner.\n",{"id":52,"difficulty":14,"q":53,"a":54},"nsubstitute-basics","How does NSubstitute differ from Moq in syntax and philosophy?","**NSubstitute** uses a leaner syntax that reads closer to plain C#. Instead of\nwrapping `Setup` and `Verify` in lambda expressions, it records the actual call\nand configures it in-place.\n\n```csharp\n\u002F\u002F Moq style:\nvar mock = new Mock\u003CICalculator>();\nmock.Setup(c => c.Add(2, 3)).Returns(5);\nvar result = mock.Object.Add(2, 3);\nmock.Verify(c => c.Add(2, 3), Times.Once);\n\n\u002F\u002F NSubstitute equivalent:\nvar sub = Substitute.For\u003CICalculator>();\nsub.Add(2, 3).Returns(5);          \u002F\u002F returns configured on the actual call\nvar result = sub.Add(2, 3);\nsub.Received(1).Add(2, 3);         \u002F\u002F verify after the fact\n\n\u002F\u002F Argument matchers in NSubstitute:\nsub.Add(Arg.Any\u003Cint>(), Arg.Any\u003Cint>()).Returns(99);\nsub.Add(Arg.Is\u003Cint>(x => x > 0), 3).Returns(42);\n\n\u002F\u002F Throwing from NSubstitute:\nsub.Add(0, 0).Throws\u003CDivideByZeroException>();\n\n\u002F\u002F Async:\nvar asyncSub = Substitute.For\u003CIOrderRepository>();\nasyncSub.GetByIdAsync(Arg.Any\u003Cint>()).Returns(Task.FromResult(new Order()));\n\n\u002F\u002F Did NOT receive — verify no call:\nasyncSub.DidNotReceive().GetByIdAsync(999);\n```\n\nNSubstitute defaults to loose behavior (unconfigured calls return defaults).\nIt does not have a strict mode, but `ReceivedCalls()` can be inspected manually.\n\n**Rule of thumb:** If you find Moq's lambda syntax noisy, try NSubstitute —\nsmaller, cleaner setup lines with the same power. The choice is largely preference;\nboth integrate with xUnit and produce equally reliable tests.\n",{"id":56,"difficulty":57,"q":58,"a":59},"mock-protected-internal","hard","How do you mock protected or internal members in Moq?","By default, Moq can only mock virtual\u002Fabstract public members. To mock\nprotected or internal members, extra configuration is required.\n\n```csharp\n\u002F\u002F Mocking a protected virtual method:\npublic class EmailService\n{\n    protected virtual bool IsValidEmail(string email)\n        => email.Contains(\"@\");\n\n    public bool SendConfirmation(string email)\n    {\n        if (!IsValidEmail(email)) throw new ArgumentException(\"Bad email\");\n        \u002F\u002F ...send...\n        return true;\n    }\n}\n\n\u002F\u002F Moq — use Protected() extension:\nusing Moq.Protected;\n\nvar mockService = new Mock\u003CEmailService>();\nmockService.Protected()\n           .Setup\u003Cbool>(\"IsValidEmail\", ItExpr.IsAny\u003Cstring>())\n           .Returns(true);\n\n\u002F\u002F Internal members — use InternalsVisibleTo in production code:\n\u002F\u002F In AssemblyInfo.cs or csproj:\n[assembly: InternalsVisibleTo(\"DynamicProxyGenAssembly2\")] \u002F\u002F Moq's proxy assembly\n[assembly: InternalsVisibleTo(\"MyApp.Tests\")]\n\n\u002F\u002F internal interface can then be mocked normally:\ninternal interface IInternalService { int Compute(); }\nvar mock = new Mock\u003CIInternalService>();\nmock.Setup(s => s.Compute()).Returns(42);\n\n\u002F\u002F Alternative: avoid mocking internals — test them through the public API,\n\u002F\u002F or extract the logic into a testable pure function.\n```\n\nTesting through protected members tightly couples tests to implementation. Only\ndo this when the protected hook is an intentional extension point.\n\n**Rule of thumb:** Prefer testing through the public API. If you find yourself\nmocking protected members frequently, consider extracting the behavior to a\ncollaborating interface instead.\n",{"id":61,"difficulty":14,"q":62,"a":63},"avoiding-over-mocking","What is over-mocking and how do you avoid it?","**Over-mocking** means replacing too many collaborators with mocks, creating\ntests that verify the implementation (call graph) rather than the behavior\n(observable outcomes). Such tests break on every refactor even when the behavior\nstays correct.\n\n```csharp\n\u002F\u002F Over-mocked — tests every internal call; fragile:\n[Fact]\npublic void PlaceOrder_OverMocked()\n{\n    var mockValidator  = new Mock\u003CIOrderValidator>();\n    var mockRepo       = new Mock\u003CIOrderRepository>();\n    var mockEmailer    = new Mock\u003CIEmailSender>();\n    var mockAuditLog   = new Mock\u003CIAuditLogger>();\n    var mockPricer     = new Mock\u003CIPricingEngine>();\n\n    mockValidator.Setup(v => v.Validate(It.IsAny\u003COrder>())).Returns(true);\n    mockPricer.Setup(p => p.Price(It.IsAny\u003COrder>())).Returns(100m);\n    \u002F\u002F ...configure 3 more mocks...\n\n    \u002F\u002F Verify ALL internal calls — test breaks if internals are refactored:\n    mockValidator.Verify(v => v.Validate(It.IsAny\u003COrder>()), Times.Once);\n    mockPricer.Verify(p => p.Price(It.IsAny\u003COrder>()), Times.Once);\n    mockAuditLog.Verify(a => a.Log(It.IsAny\u003Cstring>()), Times.Once);\n}\n\n\u002F\u002F Better — mock only external \u002F slow \u002F side-effecting dependencies:\n[Fact]\npublic void PlaceOrder_FocusedMock()\n{\n    \u002F\u002F Only mock what crosses a process boundary or has side effects:\n    var mockEmailer = new Mock\u003CIEmailSender>(); \u002F\u002F side effect: sends email\n    var mockRepo    = new Mock\u003CIOrderRepository>(); \u002F\u002F side effect: writes DB\n    mockRepo.Setup(r => r.Save(It.IsAny\u003COrder>())).Returns(true);\n\n    var service = new OrderService(\n        new OrderValidator(),   \u002F\u002F real implementation\n        mockRepo.Object,\n        new PricingEngine(),    \u002F\u002F real implementation\n        mockEmailer.Object);\n\n    service.PlaceOrder(new Order { Sku = \"X\", Quantity = 1 });\n\n    \u002F\u002F Assert behavior, not call graph:\n    mockEmailer.Verify(e => e.Send(It.IsAny\u003Cstring>(), It.IsAny\u003Cstring>()), Times.Once);\n}\n```\n\n**Rule of thumb:** Only mock collaborators that cross a process or I\u002FO boundary.\nUse real implementations for same-process logic. If replacing a real object with\na mock does not make the test faster or more reliable, skip the mock.\n",{"id":65,"difficulty":57,"q":66,"a":67},"mocking-httpclient","How do you mock HttpClient in .NET unit tests?","`HttpClient` is a concrete class, not an interface, making it awkward to mock\ndirectly. The standard approach is to mock the underlying `HttpMessageHandler`.\n\n```csharp\n\u002F\u002F Option 1: mock HttpMessageHandler (low-level but precise):\npublic class MockHttpMessageHandler : HttpMessageHandler\n{\n    private readonly HttpResponseMessage _response;\n    public MockHttpMessageHandler(HttpResponseMessage response)\n        => _response = response;\n\n    protected override Task\u003CHttpResponseMessage> SendAsync(\n        HttpRequestMessage request, CancellationToken ct)\n        => Task.FromResult(_response);\n}\n\n[Fact]\npublic async Task GetProduct_ReturnsDeserializedProduct()\n{\n    var json     = \"\"\"{\"id\":1,\"name\":\"Widget\"}\"\"\";\n    var handler  = new MockHttpMessageHandler(\n        new HttpResponseMessage(HttpStatusCode.OK)\n        {\n            Content = new StringContent(json, Encoding.UTF8, \"application\u002Fjson\")\n        });\n    var httpClient = new HttpClient(handler) { BaseAddress = new Uri(\"https:\u002F\u002Fapi.example.com\") };\n    var service    = new ProductService(httpClient);\n\n    var product = await service.GetProductAsync(1);\n\n    Assert.Equal(\"Widget\", product.Name);\n}\n\n\u002F\u002F Option 2: inject IHttpClientFactory and mock it (recommended in ASP.NET Core):\nvar mockFactory = new Mock\u003CIHttpClientFactory>();\nmockFactory.Setup(f => f.CreateClient(It.IsAny\u003Cstring>()))\n           .Returns(new HttpClient(handler) { BaseAddress = new Uri(\"https:\u002F\u002Fapi.example.com\") });\n\n\u002F\u002F Option 3: third-party — RichardSzalay.MockHttp (fluent syntax):\n\u002F\u002F var mockHttp = new MockHttpMessageHandler();\n\u002F\u002F mockHttp.When(\"\u002Fproducts\u002F1\").Respond(\"application\u002Fjson\", json);\n\u002F\u002F var client = mockHttp.ToHttpClient();\n```\n\n**Rule of thumb:** Always inject `HttpClient` or `IHttpClientFactory` via\ndependency injection — never `new HttpClient()` inside a class. That makes\nthe handler swappable in tests.\n",{"id":69,"difficulty":57,"q":70,"a":71},"mock-readonly-properties","How do you mock a property that has no setter in Moq?","Moq can mock read-only (get-only) properties on interfaces. For classes,\nthe property must be `virtual`. Concrete properties without `virtual`\ncannot be mocked.\n\n```csharp\n\u002F\u002F Interface with get-only property — Moq handles it easily:\npublic interface IUserContext\n{\n    string UserId { get; }\n    bool   IsAdmin { get; }\n}\n\nvar mockCtx = new Mock\u003CIUserContext>();\nmockCtx.Setup(c => c.UserId).Returns(\"user-42\");\nmockCtx.Setup(c => c.IsAdmin).Returns(true);\n\n\u002F\u002F Verify property access (rarely needed; prefer asserting behavior):\nmockCtx.VerifyGet(c => c.IsAdmin, Times.Once);\n\n\u002F\u002F Class with virtual get-only property:\npublic class AppContext\n{\n    public virtual string TenantId { get; } = \"default\";\n}\n\nvar mockAppCtx = new Mock\u003CAppContext>();\nmockAppCtx.Setup(c => c.TenantId).Returns(\"tenant-99\");\n\n\u002F\u002F Auto-property setup — SetupAllProperties() populates all settable properties:\nvar mockConfig = new Mock\u003CIConfiguration>();\nmockConfig.SetupAllProperties();\nmockConfig.Object.ConnectionString = \"...\"; \u002F\u002F now works for settable properties\n\n\u002F\u002F If the property is concrete and non-virtual you cannot mock it:\n\u002F\u002F Either refactor the class to use an interface,\n\u002F\u002F or use a wrapper class that implements the interface.\n```\n\n**Rule of thumb:** Design production classes to expose dependencies through\ninterfaces. If you're fighting Moq to mock a concrete property, it's usually\na sign the class needs an interface.\n",{"id":73,"difficulty":57,"q":74,"a":75},"mock-events","How do you raise events on a mock object using Moq?","Moq can simulate event raising on a mocked interface so you can test code\nthat subscribes to events without wiring up a real event source.\n\n```csharp\npublic interface IStockTickerService\n{\n    event EventHandler\u003CPriceChangedEventArgs> PriceChanged;\n    void Start();\n}\n\npublic class PortfolioMonitor\n{\n    private readonly IStockTickerService _ticker;\n    public decimal LastPrice { get; private set; }\n\n    public PortfolioMonitor(IStockTickerService ticker)\n    {\n        _ticker = ticker;\n        _ticker.PriceChanged += OnPriceChanged;\n    }\n\n    private void OnPriceChanged(object? sender, PriceChangedEventArgs e)\n        => LastPrice = e.NewPrice;\n}\n\n[Fact]\npublic void PortfolioMonitor_WhenPriceChanges_UpdatesLastPrice()\n{\n    var mockTicker = new Mock\u003CIStockTickerService>();\n\n    \u002F\u002F Subscribe the real object to the mock's event:\n    var monitor = new PortfolioMonitor(mockTicker.Object);\n\n    \u002F\u002F Raise the event on the mock — passes args to all subscribers:\n    mockTicker.Raise(\n        t => t.PriceChanged += null,\n        new PriceChangedEventArgs { Symbol = \"ACME\", NewPrice = 42.50m });\n\n    Assert.Equal(42.50m, monitor.LastPrice);\n\n    \u002F\u002F Raise multiple times to test accumulated state:\n    mockTicker.Raise(\n        t => t.PriceChanged += null,\n        new PriceChangedEventArgs { Symbol = \"ACME\", NewPrice = 55.00m });\n\n    Assert.Equal(55.00m, monitor.LastPrice);\n}\n```\n\nFor `EventHandler` (no custom args), pass `EventArgs.Empty` as the second\nargument to `Raise`. For `Action`-based events (common in modern APIs),\nuse `Raise` with a matching delegate signature.\n\n**Rule of thumb:** Use `mock.Raise(...)` to test event-driven code without\nbuilding a real event source. Keep raised events simple — complex event\nchoreography is a sign the subscriber needs its own unit test.\n",{"id":77,"difficulty":14,"q":78,"a":79},"automocking-containers","What is an auto-mocking container and when is it useful?","An **auto-mocking container** (such as `AutoMocker` from Moq.AutoMock or\n`AutoFixture` + `AutoMoqCustomization`) automatically creates mocks for all\nconstructor dependencies, so tests only configure the mocks they care about.\n\n```csharp\n\u002F\u002F Without auto-mocking — boilerplate grows with every new dependency:\n[Fact]\npublic void WithoutAutoMock_BoilerplateHeavy()\n{\n    var mockRepo    = new Mock\u003CIOrderRepository>();\n    var mockEmailer = new Mock\u003CIEmailSender>();\n    var mockLogger  = new Mock\u003CILogger\u003COrderService>>();\n    var mockClock   = new Mock\u003CIClock>();\n    \u002F\u002F ...and so on for every constructor param\n\n    var service = new OrderService(\n        mockRepo.Object, mockEmailer.Object,\n        mockLogger.Object, mockClock.Object);\n\n    mockRepo.Setup(r => r.Save(It.IsAny\u003COrder>())).Returns(true);\n    service.PlaceOrder(new Order { Sku = \"X\" });\n    mockEmailer.Verify(e => e.Send(It.IsAny\u003Cstring>(), It.IsAny\u003Cstring>()), Times.Once);\n}\n\n\u002F\u002F With AutoMocker — only touch the mocks that matter:\n\u002F\u002F dotnet add package Moq.AutoMock\n[Fact]\npublic void WithAutoMock_LessBoilerplate()\n{\n    var mocker  = new AutoMocker();\n\n    \u002F\u002F AutoMocker resolves all constructor params automatically:\n    var service = mocker.CreateInstance\u003COrderService>();\n\n    \u002F\u002F Configure only what this test cares about:\n    mocker.GetMock\u003CIOrderRepository>()\n          .Setup(r => r.Save(It.IsAny\u003COrder>()))\n          .Returns(true);\n\n    service.PlaceOrder(new Order { Sku = \"X\" });\n\n    \u002F\u002F Verify on the auto-created mock:\n    mocker.GetMock\u003CIEmailSender>()\n          .Verify(e => e.Send(It.IsAny\u003Cstring>(), It.IsAny\u003Cstring>()), Times.Once);\n}\n```\n\nAuto-mocking containers also insulate tests from constructor signature\nchanges — adding a new dependency does not break existing tests that do\nnot use that dependency.\n\n**Rule of thumb:** Introduce an auto-mocking container when a class has\nfour or more injected dependencies and most tests only touch one or two\nof them. For simpler classes, manual `new Mock\u003CT>()` is less magic and\neasier to read.\n",{"id":81,"difficulty":57,"q":82,"a":83},"mock-abstract-class","How do you mock an abstract class in Moq?","Moq can mock abstract classes directly — it creates a concrete subclass at\nruntime. Only `abstract` and `virtual` members can be overridden; concrete\nmembers run their real implementation.\n\n```csharp\npublic abstract class ReportGenerator\n{\n    \u002F\u002F Abstract — must be overridden; Moq will mock this:\n    public abstract IEnumerable\u003Cstring> FetchData();\n\n    \u002F\u002F Virtual — can be overridden in tests:\n    public virtual string FormatRow(string row) => row.ToUpperInvariant();\n\n    \u002F\u002F Concrete — Moq cannot intercept this; real code runs:\n    public string BuildReport()\n    {\n        var rows = FetchData();           \u002F\u002F will call mock\n        return string.Join(\"\\n\", rows.Select(FormatRow));\n    }\n}\n\n[Fact]\npublic void BuildReport_FormatsAllFetchedRows()\n{\n    var mockGen = new Mock\u003CReportGenerator>();\n\n    \u002F\u002F Setup the abstract method:\n    mockGen.Setup(g => g.FetchData())\n           .Returns(new[] { \"alpha\", \"beta\", \"gamma\" });\n\n    \u002F\u002F CallBase = true makes concrete methods (BuildReport) execute for real:\n    mockGen.CallBase = true;\n\n    var report = mockGen.Object.BuildReport();\n\n    Assert.Contains(\"ALPHA\", report);\n    Assert.Contains(\"BETA\",  report);\n}\n\n\u002F\u002F Mocking only the virtual override to inject alternative formatting:\nmockGen.Setup(g => g.FormatRow(It.IsAny\u003Cstring>()))\n       .Returns\u003Cstring>(r => $\"[{r}]\");\n\n\u002F\u002F Warning: do not mock concrete (non-virtual) methods —\n\u002F\u002F Moq will silently ignore the Setup and the real method runs instead.\n```\n\nSetting `mock.CallBase = true` is essential when testing a concrete method\non an abstract class — without it the concrete method returns the default\nvalue instead of executing real logic.\n\n**Rule of thumb:** Prefer interfaces over abstract classes for dependencies\nyou intend to mock. Mock abstract classes only when the class provides shared\nconcrete behavior (a template method pattern) that you want to test through.\n",15,null,{"description":11},"Mocking interview questions — Moq Setup and Verify, NSubstitute, strict vs loose mocks, argument matchers, callback captures, and over-mocking.","dotnet\u002Ftesting\u002Fmocking","Testing","testing","2026-06-23","OeEbaBeaQ1vAOz8V04fbRETn4y8T0s3pKy9cMEf13VA",[94,98,99],{"subtopic":95,"path":96,"order":97},"Unit Testing","\u002Fdotnet\u002Ftesting\u002Funit-testing",1,{"subtopic":6,"path":20,"order":12},{"subtopic":100,"path":101,"order":102},"Integration Testing","\u002Fdotnet\u002Ftesting\u002Fintegration-testing",3,{"path":104,"title":105},"\u002Fblog\u002Fdotnet-mocking","Mocking in .NET with Moq and NSubstitute",1782244119998]