开发者

Mock IServiceProvider

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜