I have a class that takes IServiceProvider as an argument in constructor, and in a Get() method it returns an object using IServiceProvider.GetRequiredService. When Unit testing this method to see whether it returns the expected Type of object, it throws System.InvalidOperationException exception with a message No service for type '..MyType..' has been registered. What should be the approach to unit test this one?

I have a restriction on changing the Get() method or Foo class implementation .Therefore, it is not an option.

Also, there were suggestions that it is not a good idea to mock IserviceProvider.GetRequiredService as this is a framework class. Therefore, haven’t used this approach.


   Public class Foo
      private IServiceProvider _serviceProvider;

      Public Foo(IServiceProvider serviceProvider, IOtherService s1, IOtherService2 s2){
         _serviceProvider = serviceProvider;
         //...mapping other dependencies here
     Public IType Get (string type){
      switch (type){

       //This line throws the DI exception when unit test
       //No service for type 'MyType' has been registered
       //Cannot change this implementation

       case "a": return (IType)_serviceProvider.GetRequiredService(typeof(MyType));

      //other cases here 

Unit test using NUnit.Framework, Autofac.Extras.Moq, Moq

public void MyTest()
  using var am = AutoMock.GetLoose();
  var foo= am.Create<Foo>();

  //DI Exception when calling this method
  //No service for type 'MyType' has been registered
 //Assert here

Really appreciate the support in resolving this.