.net 模拟IServiceProvider

cld4siwp  于 2022-12-14  发布在  .NET
关注(0)|答案(1)|浏览(112)

I'm still learning C# and.Net. Trying to create a mock so that I can test my factory class:

public class PublishServiceClientFactory
{
    /// <summary>
    /// method <c>GetInstance</c> creates a PublishServiceClient
    /// instantiation
    /// </summary>
    /// <param name="serviceProvider"></param>
    /// <returns>PublishServiceClient</returns>
    public static IPublishServiceClient GetInstance(IServiceProvider serviceProvider)
    {
        var options = serviceProvider.GetService<IOptions<PublishServiceClientConfiguration>>();
        var configuration = options.Value;
        var logger = serviceProvider.GetService<ILogger<PublishServiceClient>>();
        var httpClient = new HttpClient
        {
            BaseAddress = new Uri(configuration.Uri)
        };

        return new PublishServiceClient(httpClient, configuration.Key, logger);
    }
}

My attempt at implementing the unit test:

public class PublishServiceClientFactoryTests
{
  private readonly  Mock<IServiceProvider> serviceProviderMock;
  
  public PublishServiceClientFactoryTests()
  {
    serviceProviderMock = new Mock<IServiceProvider>();

  }
  
  [Fact]
  public void GetInstance_Returns_instance_of_PublishServiceClient()
  {
    // arrange
    serviceProviderMock
      .Setup(x
        => x.GetService<IOptions<PublishServiceClientConfiguration>>())
      .Returns(new PublishServiceClientConfiguration());

    // act
    var result = PublishServiceClientFactory.GetInstance(serviceProviderMock.Object);
    
    // assert
    Assert.NotNull(result);
  }
}

I've been banging my head for a few hours. Took a look a this issue but was unable to resolve. Any help will be appreciated.

zvms9eto

zvms9eto1#

I think you can avoiding mocks for your scenario, but create actual service provider instead.

// Arrange
var services = new ServiceCollection();
services.Configure<PublishServiceClientConfiguration>(
    config => config.ClientProperty = "my test value"
);

var provider = services.BuildServiceProvider();

// Act
var result = PublishServiceClientFactory.GetInstance(provider);

// Assert
result.Value.ClientProperty.Should().Be("my test value");

相关问题