Unit Test and Mock IOptions <T> .NET Core

Today in this article, we shall see how to Unit Test and Mock IOptions <T> instance often used in Controller or other modules for injecting the configuration details.

Updated November 2026: sections on mocking IOptionsMonitor and IOptionsSnapshot, named options and validation, plus an FAQ.

Today in this article, we will cover below aspects,

The IOptions interface pattern provides access to configuration details in related classes as well as
the option to load config data depending on the situation.

The IOptions interface will be used to load the configuration as needed in the program.

Example:

public class ProducerController : ControllerBase
     {
         readonly ProducerConfigSettings _producerConfigSetting;
         public ProducerController(IOptions producerConfig)
         {
             _producerConfigSetting = producerConfig.Value;
         }

.

.
     }

The above shows ProducerController which is a controller class injecting Apsettings.json key-value pair using the IOption pattern.

For more details on IOption Pattern, please visit the below article,

Unit test IOption without Mock

In this approach, you certainly need not have to mock the Apsettings object. You can send test settings details via the settings object as below and test all positive and negative scenarios as required.

Example

            //Arrange
            ProducerConfigSettings appSettings = new ProducerConfigSettings() 
            { 
                Key1 = "testkey1",
                Key2 = "Testkey2" 
            };
            IOptions<ProducerConfigSettings> options = Options.Create(appSettings);
            ProducerController controller = new ProducerController(options);


Unit Test and Mock IOptions

Unit Test IOption by Mock IOption

In this approach, you can mock the Apsettings object. You can send mocked settings details via the settings object as below and test all positive and negative scenarios as required.

           //Arrange
            ProducerConfigSettings appSettings = new ProducerConfigSettings()
            {
                Key1 = "testkey1",
                Key2 = "Testkey2"
            };
            var mockIOption = new Mock<IOptions<ProducerConfigSettings>>();
            // We need to set the Value of IOptions to be the SampleOptions Class
            mockIOption.Setup(ap => ap.Value).Returns(appSettings);
            ProducerController controller = new ProducerController(mockIOption.Object);


Mock IOptions .net core, unit test IOptions

Finally, Using any of the above approaches when you run the test cases, it starts using test/mocked app settings, instead of pulling it from the actual apsettings.json file.

Unit Test IOptions

References:

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published (2026) best practices and guidelines for software design and development.



How to Mock IOptionsMonitor and IOptionsSnapshot in a Unit Test

You can’t use Options.Create for these two interfaces, because it only returns IOptions<T>. For IOptionsMonitor<T> and IOptionsSnapshot<T> you need a stub, a mock or a small hand-written fake.

How do you stub IOptionsMonitor with Moq or NSubstitute?

IOptionsMonitor<T> exposes CurrentValue, not Value, so that’s the member you set up. A stub is a test double that returns a canned answer and nothing more.

Note: A stub is like a cardboard cut-out of a shop assistant. It stands in the right place and gives the answer you taped to it, but it can’t react when you change something.

  • Moq: create a Mock<IOptionsMonitor<ProducerConfigSettings>>, call Setup(o => o.CurrentValue).Returns(appSettings), then pass .Object to your class. Mock.Of<IOptionsMonitor<ProducerConfigSettings>>(m => m.CurrentValue == appSettings) does the same in one line.
  • NSubstitute: call Substitute.For<IOptionsMonitor<ProducerConfigSettings>>(), then monitor.CurrentValue.Returns(appSettings).
  • IOptionsSnapshot: same approach, but you set up Value. Remember it’s scoped, so a stub won’t warn you if you inject it into a singleton. That mistake only shows up at runtime in the real container.

If your code calls Get(name), set that up too. A loose mock returns null for unconfigured calls.

How do you simulate a configuration reload without a mocking library?

Write a small fake that implements IOptionsMonitor<T> and can raise its own change notification. A fake is a working lightweight implementation, unlike a stub, which only returns fixed values.

The fake needs four members:

  • CurrentValue: returns the stored settings object.
  • Get(name): returns the stored object, or one per name if you test named options.
  • OnChange: saves the listener and returns an IDisposable that removes it.
  • Set: replaces the stored value, then calls the listener with the new value and a name.

How do you test a class that reacts to OnChange?

Build the fake with starting settings, construct the consumer, call Set, and assert the new behaviour. Say a service subscribes in its constructor and caches Key1.

  1. Arrange: create the fake with Key1 = "testkey1" and pass it to the service.
  2. Assert the baseline: check the service uses testkey1 before any reload.
  3. Act: call Set with Key1 = "newkey".
  4. Assert the change: check the service now uses newkey.

Mock library or hand-written fake?

Use Moq or NSubstitute for one-off stubs where a test only reads CurrentValue. Write the fake once you have several tests that need reload behaviour, because wiring up callbacks with a mocking library in each test gets noisy fast.

Frequently asked questions

Do I need Moq to mock IOptions<T>, or is Options.Create enough?

No, Options.Create is enough. Options.Create(new T { ... }) in Microsoft.Extensions.Options wraps the instance in an OptionsWrapper<T> and returns IOptions<T>, so you need no mocking library and no DI container. Use Moq with Setup(x => x.Value).Returns(...) only if your test project already uses it, because a real instance is simpler and has nothing to configure.

How do I mock IOptionsMonitor<T> and its CurrentValue?

Use a mocking library or a stub, because Options.Create can’t build an IOptionsMonitor<T>. With Moq, call Setup(o => o.CurrentValue).Returns(value) or use Mock.Of<IOptionsMonitor<T>>(m => m.CurrentValue == value). With NSubstitute, create it with Substitute.For<IOptionsMonitor<T>>() and then call CurrentValue.Returns(value).

If you need to test OnChange behaviour, write a small fake class that implements the interface. Give it a Set method that stores the new value and calls the registered listener, so the test can simulate a configuration reload.

Why does IOptions<T>.Value return an unconfigured object in my test?

Because Value reads the default, empty-string name, and nothing populated that instance. If the options were configured under a name, or the test never set any properties, you get a default object with no error. Use Options.Create with populated values instead. For named options, inject IOptionsMonitor<T> or IOptionsSnapshot<T> and call Get(name).

Should I build a real configuration with ConfigurationBuilder in tests instead of a mock?

Yes, when the thing under test is the configuration itself. Use a real in-memory configuration (AddInMemoryCollection with Bind or services.Configure) to check section names, binding and validation. For testing a consumer’s logic, such as the controller in this article, Options.Create is simpler and keeps the test focused on your own code.

2 thoughts on “Unit Test and Mock IOptions in .NET Core”

Leave a Reply

Your email address will not be published. Required fields are marked *