Mocking and integration tests
Mocking replaces external dependencies (payment APIs, the clock) with test doubles so unit tests stay fast and reliable, and integration tests run the whole ASP.NET Core API in memory with WebApplicationFactory and a real-SQL test database.
68.1 Why is it used?
- In the demo the OrderService test creates a real UpiPaymentGateway with a new HttpClient.
- Without a network the test fails with "No such host is known", even though there is no bug.
- If the server is up, the test might charge real money.
- Fix: a fake object that the test controls, called a test double.
C#
[Fact]public async Task Place_PaymentOk_ReturnsOrder(){ var payments = new UpiPaymentGateway( new HttpClient()); var sut = new OrderService( payments, TimeProvider.System); var order = await sut.PlaceAsync("Amit", 499m); order.ShouldNotBeNull();}Output
$ dotnet test --filter OrderServiceBugTests Failed OrderServiceBugTests.Place_PaymentOk_ReturnsOrder [2 s] Error Message: System.Net.Http.HttpRequestException : No such host is known. (api.upi-pay.example:443)---- System.Net.Sockets.SocketException : No such host is known.Failed! - Failed: 1, Passed: 0, Skipped: 0, Total: 1, Duration: 2 s68.2 Step 1: inject an interface
- OrderService takes IPaymentGateway and TimeProvider through its constructor (DI).
- Now a test can pass its own versions of both.
- Payment failure returns null; otherwise the order time comes from TimeProvider.
C#
public class OrderService( IPaymentGateway payments, TimeProvider time){ public async Task<Order?> PlaceAsync( string customer, decimal amount) { var paid = await payments .ChargeAsync(customer, amount); if (!paid) return null; return new Order(customer, amount, time.GetUtcNow()); }}68.3 NSubstitute: Returns, Received, Arg.Any
- Substitute.For<IPaymentGateway>() creates a fake.
- .Returns(true) sets the answer for ChargeAsync("Amit", 499m).
- Received(1) verifies that ChargeAsync was called exactly once.
- Arg.Any<string>() / Arg.Any<decimal>() match any value; Returns(false) builds the payment-failed case.
- Both tests pass with no network call.
C#
[Fact]public async Task Place_PaymentOk_ReturnsOrder(){ var payments = Substitute.For<IPaymentGateway>(); payments.ChargeAsync("Amit", 499m) .Returns(true); var sut = new OrderService( payments, TimeProvider.System); var order = await sut.PlaceAsync("Amit", 499m); order.ShouldNotBeNull(); await payments.Received(1) .ChargeAsync("Amit", 499m);}Output
$ dotnet test --filter Place_PaymentOk Passed OrderServiceTests.Place_PaymentOk_ReturnsOrder [448 ms]Test Run Successful.Total tests: 1 Passed: 1C#
[Fact]public async Task Place_PaymentFails_ReturnsNull(){ var payments = Substitute.For<IPaymentGateway>(); payments.ChargeAsync( Arg.Any<string>(), Arg.Any<decimal>()) .Returns(false); var sut = new OrderService( payments, TimeProvider.System); var order = await sut.PlaceAsync("Ravi", 50000m); order.ShouldBeNull();}Output
$ dotnet test --filter Place_ Passed OrderServiceTests.Place_PaymentFails_ReturnsNull [458 ms] Passed OrderServiceTests.Place_PaymentOk_ReturnsOrder [41 ms]Test Run Successful.Total tests: 2 Passed: 268.4 Stub, mock and fake
| Test double | What it does | Example here |
|---|---|---|
| Stub | Gives a fixed answer | payments.ChargeAsync(...).Returns(true) |
| Mock | Also verifies the call happened | payments.Received(1).ChargeAsync("Amit", 499m) |
| Fake | Light working version of a dependency | FakeTimeProvider, SQLite in-memory DB |
- Moq is also common and capable; in 2023 one version shipped SponsorLink, which checked a hash of the developer's email during build, and it was removed after the controversy.
68.5 FakeTimeProvider: control time
- Rule: an order can be cancelled only within 30 minutes.
- FakeTimeProvider is a clock that does not move on its own.
- Advance(29 min) -> CanCancel true; Advance(2 more) -> false, with no real waiting.
C#
[Fact]public void CanCancel_After31Minutes_IsFalse(){ var clock = new FakeTimeProvider(); var sut = new OrderService( Substitute.For<IPaymentGateway>(), clock); var order = new Order( "Amit", 499m, clock.GetUtcNow()); clock.Advance(TimeSpan.FromMinutes(29)); sut.CanCancel(order).ShouldBeTrue(); clock.Advance(TimeSpan.FromMinutes(2)); sut.CanCancel(order).ShouldBeFalse();}Output
$ dotnet test --filter CanCancel Passed OrderServiceTests.CanCancel_After31Minutes_IsFalse [351 ms]Test Run Successful.Total tests: 1 Passed: 168.6 WebApplicationFactory and the test database
- WebApplicationFactory<Program> (Microsoft.AspNetCore.Mvc.Testing) starts the API inside the test; in .NET 10 Program is public automatically.
- ConfigureTestServices replaces real services: payment -> substitute, TimeProvider -> FakeTimeProvider.
- UseTestDatabase opens a SQLite in-memory connection; the DB lives as long as the connection stays open.
- EnsureCreated creates the tables; RemoveAll removes the real DbContextOptions and the test options are registered.
C#
public class ShopFactory : WebApplicationFactory<Program>{ public IPaymentGateway Payments = Substitute.For<IPaymentGateway>(); public FakeTimeProvider Clock = new(); protected override void ConfigureWebHost( IWebHostBuilder builder) => builder.ConfigureTestServices(s => { s.UseTestDatabase(); s.AddSingleton(Payments); s.AddSingleton<TimeProvider>(Clock); });}C#
public static void UseTestDatabase( this IServiceCollection s){ var db = new SqliteConnection( "DataSource=:memory:"); db.Open(); var options = new DbContextOptionsBuilder<ShopDb>() .UseSqlite(db).Options; using var ctx = new ShopDb(options); ctx.Database.EnsureCreated(); s.RemoveAll<DbContextOptions<ShopDb>>(); s.AddSingleton(options);}68.7 Integration tests
- IClassFixture<ShopFactory> shares one factory across the tests in the class.
- CreateClient gives an HttpClient that sends requests to the in-memory app.
- POST /orders runs the real endpoint, EF Core and SQLite: 201 Created.
- The same FakeTimeProvider works inside the app: advance 31 minutes, DELETE gives 409 Conflict.
C#
public class OrdersApiTests(ShopFactory app) : IClassFixture<ShopFactory>{ [Fact] public async Task Post_PaymentOk_Returns201() { app.Payments.ChargeAsync("Amit", 499m) .Returns(true); var client = app.CreateClient(); var res = await client.PostAsJsonAsync( "/orders", new PlaceOrder("Amit", 499m)); res.StatusCode.ShouldBe( HttpStatusCode.Created); } [Fact] public async Task Cancel_After31Min_Returns409() { app.Payments.ChargeAsync("Ravi", 999m) .Returns(true); var client = app.CreateClient(); var res = await client.PostAsJsonAsync( "/orders", new PlaceOrder("Ravi", 999m)); var url = res.Headers.Location; app.Clock.Advance(TimeSpan.FromMinutes(31)); var cancel = await client.DeleteAsync(url); cancel.StatusCode.ShouldBe( HttpStatusCode.Conflict); }}Output
$ dotnet test --filter OrdersApiTests Passed OrdersApiTests.Post_PaymentOk_Returns201 [5 s] Passed OrdersApiTests.Cancel_After31Min_Returns409 [1 s]Test Run Successful.Total tests: 2 Passed: 2- Step 1
1.WebApplicationFactory<Program> starts the API in memory (TestServer, no port)
- Step 2
2.ConfigureTestServices swaps in fake payment, FakeTimeProvider and the SQLite test DB
- Step 3
3.CreateClient() gives an HttpClient wired to the in-memory app
- Step 4
4.POST /orders goes through real routing, DI, EF Core and SQLite: 201 Created
- Step 5
5.Clock.Advance(31 min), DELETE the order URL: 409 Conflict
- Step 6
6.Assert the status codes and data
68.8 Checkpoint: connection string instead of an open connection
- Passing "DataSource=:memory:" as a string to UseSqlite gives "no such table: Orders" and a 500.
- In-memory SQLite creates a new empty database for every new connection, so the tables from EnsureCreated vanish when its connection closes.
- Always open the SqliteConnection yourself and keep it open.
C#
var options = new DbContextOptionsBuilder<ShopDb>() .UseSqlite("DataSource=:memory:") .Options;using var ctx = new ShopDb(options);ctx.Database.EnsureCreated();s.RemoveAll<DbContextOptions<ShopDb>>();s.AddSingleton(options);Output
$ dotnet test --filter OrdersApiTestsfail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] ---> Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'no such table: Orders'. Failed OrdersApiTests.Post_PaymentOk_Returns201 [5 s] Shouldly.ShouldAssertException : res.StatusCode should beHttpStatusCode.Created but wasHttpStatusCode.InternalServerError68.9 Comparison: unit vs integration tests
| Point | Unit test | Integration test (WebApplicationFactory) |
|---|---|---|
| Scope | One class (OrderService) | Whole API: routing, DI, EF Core, DB |
| Dependencies | Mocked (NSubstitute) / fake clock | Real app; only boundaries replaced via ConfigureTestServices |
| Speed | Milliseconds | Seconds (app startup) |
| How many | Many, for logic | A few, for endpoints |
68.10 Common mistakes
- Real external services in tests: flaky, slow, can cost money.
- EF Core InMemory provider as the test DB: not relational, ignores unique indexes (saved two DIWALI50 coupons). Use SQLite or Testcontainers.
- Mocking everything: mock only boundaries (payment, email, external APIs); keep your own logic real.
- Using DateTime.Now in code: inject TimeProvider so tests can control time.
- Thinking WebApplicationFactory opens a real port: it uses TestServer in memory, Kestrel does not run.
- Tests sharing data: every test should create its own data.
C#
// Wrong: EF Core InMemory provider, not relationalvar options = new DbContextOptionsBuilder<CouponDb>() .UseInMemoryDatabase("shop") .Options;// unique index on Coupon.Code// 2x Add("DIWALI50") + SaveChanges()// InMemory: saved 2 duplicates // Right: SQLite in-memory runs real SQLvar db = new SqliteConnection( "DataSource=:memory:");db.Open();var options = new DbContextOptionsBuilder<CouponDb>() .UseSqlite(db).Options;// same 2x Add("DIWALI50") + SaveChanges()// SQLite Error 19: 'UNIQUE constraint// failed: Coupons.Code'68.11 Interview tips
- Unit-test business logic with NSubstitute mocks for external dependencies; FakeTimeProvider for time.
- Returns = stub, Received = verify (mock).
- Endpoints: WebApplicationFactory runs the app in memory; ConfigureTestServices swaps dependencies.
- Test DB: SQLite in-memory with an open connection, or Testcontainers; not the InMemory provider.
- Many fast unit tests, a few integration tests.