---
title: "ASP.NET Core Integration Testing & Mocking using Moq - Muhammad Rehan Saeed"
description: "Mocking services using Moq while integration testing ASP.NET Core applications in memory."
canonical_url: "https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/"
last_updated: "2020-01-03T00:00:00+00:00"
meta:
  author: "Muhammad Rehan Saeed"
  keywords: "ASP.NET Core,Integration Tests,Mock,Moq,xUnit"
  "og:description": "Mocking services using Moq while integration testing ASP.NET Core applications in memory."
  "og:image": "https://rehansaeed.com/_og/s/o_8748c212d11f0225.png"
  "og:image:alt": "ASP.NET Core Integration Testing & Mocking using Moq - Muhammad Rehan Saeed"
  "og:image:height": "630"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "ASP.NET Core Integration Testing & Mocking using Moq"
  "twitter:image": "https://rehansaeed.com/_og/s/o_8748c212d11f0225.png"
  "twitter:image:alt": "ASP.NET Core Integration Testing & Mocking using Moq - Muhammad Rehan Saeed"
---

> Index of every page on this site: [llms.txt](https://rehansaeed.com/llms.txt)

# [ASP.NET Core Integration Testing & Mocking using Moq](https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/)

Posted 3 January 2020 - **4 min read**

![Microsoft .NET](https://rehansaeed.com/_ipx/f_png&s_2560x1440/images/hero/Microsoft-.NET-1366x768.png)

If you want to run an integration test for your ASP.NET Core app without also testing lots of external dependencies like databases and the like, then the **lengthy** official ' [Integration tests in ASP.NET Core](https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2)' documentation shows how you can use stubs to replace code that talks to a database or some other external service. If you want to use mocks using [Moq](https://github.com/moq/moq4), this is where you run out of guidance and runway. It does in fact require a fair amount of setup to do it correctly and reliably without getting flaky tests.

# Startup

The `ConfigureServices` and `Configure` methods in your applications `Startup` class must be `virtual`. This is so that we can inherit from this class in our tests and replace production versions of certain services with mock versions.

```cs
public class Startup
{
    private readonly IConfiguration configuration;
    private readonly IWebHostingEnvironment webHostingEnvironment;

    public Startup(
        IConfiguration configuration,
        IWebHostingEnvironment webHostingEnvironment)
    {
        this.configuration = configuration;
        this.webHostingEnvironment = webHostingEnvironment;
    }

    public virtual void ConfigureServices(IServiceCollection services) => ...

    public virtual void Configure(IApplicationBuilder application) => ...
}
```

# TestStartup

In your test project, inherit from the `Startup` class and override the `ConfigureServices` method with one that registers the mock and the mock object with IoC container.

I like to use strict mocks using `MockBehavior.Strict`, this ensures that nothing is mocked unless I specifically setup a mock.

```cs
public class TestStartup : Startup
{
    private readonly Mock clockServiceMock;

    public TestStartup(
        IConfiguration configuration,
        IHostingEnvironment hostingEnvironment)
        : base(configuration, hostingEnvironment)
    {
        this.clockServiceMock = new Mock(MockBehavior.Strict);
    }

    public override void ConfigureServices(IServiceCollection services)
    {
        services
            .AddSingleton(this.clockServiceMock);

        base.ConfigureServices(services);

        services
            .AddSingleton(this.clockServiceMock.Object);
    }
}
```

# CustomWebApplicationFactory

In your test project, write a custom `WebApplicationFactory` that configures the `HttpClient` and resolves the mocks from the `TestStartup`, then exposes them as properties, ready for our integration test to consume them. Note that I'm also changing the environment to `Testing` and telling it to use the `TestStartup` class for startup.

Note also that I've implemented `IDisposable`'s `Dispose` method to verify all of my strict mocks. This means I don't need to verify any mocks manually myself. Verification of all mock setups happens automatically when xUnit is disposing the test class.

```cs
public class CustomWebApplicationFactory : WebApplicationFactory
    where TEntryPoint : class
{
    public CustomWebApplicationFactory()
    {
        this.ClientOptions.AllowAutoRedirect = false;
        this.ClientOptions.BaseAddress = new Uri("https://localhost");
    }

    public ApplicationOptions ApplicationOptions { get; private set; }

    public Mock ClockServiceMock { get; private set; }

    public void VerifyAllMocks() => Mock.VerifyAll(this.ClockServiceMock);

    protected override void ConfigureClient(HttpClient client)
    {
        using (var serviceScope = this.Services.CreateScope())
        {
            var serviceProvider = serviceScope.ServiceProvider;
            this.ApplicationOptions = serviceProvider
                .GetRequiredService<IOptions<ApplicationOptions>>().Value;
            this.ClockServiceMock = serviceProvider
                .GetRequiredService<Mock<IClockService>>();
        }

        base.ConfigureClient(client);
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder) =>
        builder
            .UseEnvironment("Testing")
            .UseStartup();

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            this.VerifyAllMocks();
        }

        base.Dispose(disposing);
    }
}
```

# Integration Tests

I'm using xUnit to write my tests. Note that the generic type passed to `CustomWebApplicationFactory` is `Startup` and not `TestStartup`. This generic type is used to find the location of your application project on disk and not to start the application.

I setup a mock in my test and I've implemented `IDisposable` to verify all mocks for all my tests at the end but you can do this step in the test method itself if you like.

Note also, that I'm not using xUnit's `IClassFixture` to only boot up the application once as the ASP.NET Core documentation tells you to do. If I did so, I'd have to reset the mocks between each test and also you would only be able to run the integration tests serially one at a time. With the method below, each test is fully isolated and they can be run in parallel. This uses up more CPU and each test takes longer to execute but I think it's worth it.

```cs
public class FooControllerTest : CustomWebApplicationFactory
{
    private readonly HttpClient client;
    private readonly Mock clockServiceMock;

    public FooControllerTest()
    {
        this.client = this.CreateClient();
        this.clockServiceMock = this.ClockServiceMock;
    }

    [Fact]
    public async Task GetFoo_Default_Returns200OK()
    {
        this.clockServiceMock
            .Setup(x => x.UtcNow)
            .ReturnsAsync(new DateTimeOffset(2000, 1, 1));

        var response = await this.client.GetAsync("/foo");

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    }
}
```

# xunit.runner.json

I'm using xUnit. We need to turn off shadow copying, so any separate files like `appsettings.json` are placed in the right place beside the application DLL file. This ensures that our application running in an integration test can still read the `appsettings.json` file.

```json
{
  "shadowCopy": false
}
```

# appsettings.Testing.json

Should you have configuration that you want to change just for your integration tests, you can add a `appsettings.Testing.json` file into your application. This configuration file will only be read in our integration tests because we set the environment name to 'Testing'.

## Working Examples

If you'd like to see an end to end working example of how this all works. You can create a project using the [Dotnet Boxed](https://github.com/Dotnet-Boxed/Templates) [API project template](https://github.com/Dotnet-Boxed/Templates/blob/main/Docs/API.md) or the [GraphQL project template](https://github.com/Dotnet-Boxed/Templates/blob/main/Docs/GraphQL.md).

## Conclusions

I wrote this because there is little to no information on how to combine ASP.NET Core with Moq in integration tests. I've messed about with using `IClassFixture` as the ASP.NET Core documentation tells you to do and it's just not a good idea with Moq which needs a clean slate before each test. I hope this stops others going through much pain.

## Web Mentions

[What's this?](https://en.wikipedia.org/wiki/Webmention)

### 0 Linked

### 0 Replies

## GitHub Comments

### 10 Comments

[Comment on GitHub](https://github.com/RehanSaeed/rehansaeed.github.io/issues/56)

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed "RehanSaeed")

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Leszek](https://camo.githubusercontent.com/64eef0937f46e1eed9a18ac3f5caf28d4b210b05cafb93748a56e5b1b9495358/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f38663632626334353935326265653433333564373437643131306237316365393f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/64eef0937f46e1eed9a18ac3f5caf28d4b210b05cafb93748a56e5b1b9495358/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f38663632626334353935326265653433333564373437643131306237316365393f733d393626643d6d6d26723d67) **Leszek** commented on **2020-01-03 13:48:39**

Thank you very much, sir.

Another good article is on https://automationrhapsody.com/net-core-integration-testing-mock-dependencies/

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed "RehanSaeed")

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Rutxifer](https://camo.githubusercontent.com/de67ce39e70c292f8b747b63e7c32b92d989a81fc1f6f8b7b643cedca1de6ad9/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f61636462363234386163656262326637386661633263343761316637303466313f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/de67ce39e70c292f8b747b63e7c32b92d989a81fc1f6f8b7b643cedca1de6ad9/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f61636462363234386163656262326637386661633263343761316637303466313f733d393626643d6d6d26723d67) **Rutxifer** commented on **2020-01-03 18:04:48**

Great article! Could be improved using `HttpClient` rather than `HttpClientFactory`?  
 How it works if web application have a lot of dependencies? All of them are stored in properties when tests starts.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed "RehanSaeed")

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2020-01-04 09:54:37**

> Great article! Could be improved using `HttpClient` rather than `HttpClientFactory`?  
>  How it works if web application have a lot of dependencies? All of them are stored in properties when tests starts.

Not sure what you mean. We're not using `HttpClientFactory`.

The only mocks you should have is for external systems like DB's.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed "RehanSaeed")

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Nicole](https://camo.githubusercontent.com/6efba5fe2fa0dd213c9b138c1aefebfa6074df63bfb77474ce2e31ae01962d5f/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f39323761646137623538613365613733353832383537666238336234346566613f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/6efba5fe2fa0dd213c9b138c1aefebfa6074df63bfb77474ce2e31ae01962d5f/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f39323761646137623538613365613733353832383537666238336234346566613f733d393626643d6d6d26723d67) **Nicole** commented on **2020-03-30 03:48:37**

Hi,

Thank you for the article.

However, I came across an issue when i tried this method.

```
this.ApplicationOptions = serviceProvider.GetRequiredService<IOptions>().Value;
```

The thing inside `IOptions` should be non-abstract, but `ApplicationOptions` is an abstract class.

Is there any possible way to fix that?

Cheers,  
 Nicole

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed "RehanSaeed")

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Milind](https://camo.githubusercontent.com/2cc7112c3b94b143fee9beee2e7cff26c253a2a3cac4982952edbda0051e563f/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f31326633636437636234373864366638376539313335643261626463653362333f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/2cc7112c3b94b143fee9beee2e7cff26c253a2a3cac4982952edbda0051e563f/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f31326633636437636234373864366638376539313335643261626463653362333f733d393626643d6d6d26723d67) **Milind** commented on **2020-04-07 07:05:32**

Getting error in `CustomWebApplicationFactory.cs` for `this.Services.CreateScope()` in `ConfigureClient` method. It does not recognize it. What is `this.Services`?

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed "RehanSaeed")

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2020-04-08 14:31:55**

> Hi,
>
> Thank you for the article.
>
> However, I came across an issue when i tried this method.
>
> ```
> this.ApplicationOptions = serviceProvider.GetRequiredService<IOptions>().Value;
> ```
>
> The thing inside `IOptions` should be non-abstract, but `ApplicationOptions` is an abstract class.
>
> Is there any possible way to fix that?
>
> Cheers,  
>  Nicole

`ApplicationOptions` is just a class that I myself wrote to contain some custom configuration options. It doesn't have to be abstract.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed "RehanSaeed")

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020 (edited 12 May 2020)

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2020-04-08 14:37:03**

> Getting error in `CustomWebApplicationFactory.cs` for `this.Services.CreateScope()` in `ConfigureClient` method. It does not recognize it. What is `this.Services`?

The class inherits from `WebApplicationFactory` and that is where the `Services` property comes from.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed "RehanSaeed")

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Neal](https://camo.githubusercontent.com/54b5dd8c52b01057ebe244431637d0e2cea6f43d0b7b2e8f69cac13c09028097/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f62633439666264326363303933323465633262353130373736333565633764303f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/54b5dd8c52b01057ebe244431637d0e2cea6f43d0b7b2e8f69cac13c09028097/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f62633439666264326363303933323465633262353130373736333565633764303f733d393626643d6d6d26723d67) **Neal** commented on **2020-04-20 20:28:28**

You don' t need to extend startup to configure your test services for dotnet core 3+. `IWebHostBuilder` has a `ConfigureTestServices` extension method that will allow you to update the service registrations. In your custom web application factory override `ConfigureWebHost` and call the `ConfigureTestServices` method from there. This is documented [here](https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1#inject-mock-services).

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed "RehanSaeed")

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Muhammad Rehan Saeed](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/8a07049df41b8a3839a3f4342f09ea8e6e7fa0065667687f04beca2d088a1dca/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32623266393030653361633066353535316462646537323864336262343935343f733d393626643d6d6d26723d67) **[Muhammad Rehan Saeed](https://rehansaeed.com/)** commented on **2020-04-21 09:33:56**

> You don' t need to extend startup to configure your test services for dotnet core 3+. `IWebHostBuilder` has a `ConfigureTestServices` extension method that will allow you to update the service registrations. In your custom web application factory override `ConfigureWebHost` and call the `ConfigureTestServices` method from there. This is documented [here](https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1#inject-mock-services).

This is true. However, there was/is a known bug that stops this working at the time of writing. Also, I find that splitting it out into a separate class is helpful.

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed "RehanSaeed")

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Jonathan](https://camo.githubusercontent.com/c1d40eaaa7a5d6b2f260372c2f99e60204cb986ce1f7a7de193c42eaca5141a0/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f64616633633032626564396432326130343232643362656364333862623464613f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/c1d40eaaa7a5d6b2f260372c2f99e60204cb986ce1f7a7de193c42eaca5141a0/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f64616633633032626564396432326130343232643362656364333862623464613f733d393626643d6d6d26723d67) **Jonathan** commented on **2020-04-21 16:47:30**

Nice article.

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://rehansaeed.com/#website","@type":"WebSite","description":"Software Developer at Microsoft, YouTuber, Open Source Contributor and Blogger","inLanguage":"en-GB","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/","author":{"@id":"https://rehansaeed.com/#identity"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://rehansaeed.com/?search={search_term_string}"},"query-input":"required name=search_term_string"}],"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/#webpage","@type":"WebPage","dateModified":"2020-01-03T00:00:00+00:00","datePublished":"2020-01-03T00:00:00+00:00","description":"Mocking services using Moq while integration testing ASP.NET Core applications in memory.","name":"ASP.NET Core Integration Testing & Mocking using Moq","url":"https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/","breadcrumb":{"@id":"https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/#breadcrumb"},"isPartOf":{"@id":"https://rehansaeed.com/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/"]}]},{"@id":"https://rehansaeed.com/#identity","@type":"Person","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/about/","image":{"@id":"https://rehansaeed.com/#/schema/image/1"},"sameAs":["https://github.com/RehanSaeed","https://www.linkedin.com/in/muhammad-rehan-saeed","https://stackoverflow.com/users/1212017/muhammad-rehan-saeed","https://www.youtube.com/c/MuhammadRehanSaeed","https://www.twitch.tv/rehansaeeduk"]},{"@id":"https://rehansaeed.com/#publisher","@type":"Organization","logo":"https://rehansaeed.com/images/schema/Publisher-600x60.png","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com"},{"@id":"https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/#article","@type":"Article","dateModified":"2020-01-03T00:00:00+00:00","datePublished":"2020-01-03T00:00:00+00:00","description":"Mocking services using Moq while integration testing ASP.NET Core applications in memory.","headline":"ASP.NET Core Integration Testing & Mocking using Moq","inLanguage":"en-GB","url":"https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/","author":{"@id":"https://rehansaeed.com/#identity"},"image":[{"@type":"ImageObject","url":"https://rehansaeed.com/images/hero/Microsoft-.NET-1366x768.png","caption":"Microsoft .NET","width":"1366","height":"768"}],"isPartOf":{"@id":"https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/#webpage"},"keywords":["ASP.NET Core","Integration Tests","Mock","Moq","xUnit"],"mainEntityOfPage":{"@id":"https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/#webpage"},"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Blog","item":"https://rehansaeed.com/","position":1},{"@type":"ListItem","name":"ASP.NET Core Integration Testing & Mocking using Moq","item":"https://rehansaeed.com/asp-net-core-integration-testing-mocking-using-moq/","position":2}]},{"@id":"https://rehansaeed.com/#/schema/image/1","@type":"ImageObject","contentUrl":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png","inLanguage":"en-GB","url":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png"}]}
```

## Sitemap

See the full [sitemap](https://rehansaeed.com/sitemap.md) for all pages.
