【问题标题】:How do I mock IConfiguration with Moq?如何使用 Moq 模拟 IConfiguration?
【发布时间】:2021-05-01 17:55:41
【问题描述】:

如何在单元测试中模拟这样的代码。我在 asp.net core 5 中使用 xUnit 和 Moq。我是 xUnit 和 Moq 的新手。

var url = configuration.GetSection("AppSettings").GetSection("SmsApi").Value;

配置对象已经被注入到构造函数中了。

这是我目前在单元测试类中的内容

public class UtilityTests
{
    private readonly Utility sut;

    public UtilityTests()
    {
        var mockConfig = new Mock<IConfiguration>();
        var mockConfigSection = new Mock<IConfigurationSection>();
        //mockConfigSection.Setup(x => x.Path).Returns("AppSettings");
        mockConfigSection.Setup(x => x.Key).Returns("SmsApi");
        mockConfigSection.Setup(x => x.Value).Returns("http://example.com");
        
        mockConfig.Setup(x => x.GetSection("AppSettings")).Returns(mockConfigSection.Object);
        
        sut = new Utility(mockConfig.Object);
    }

    [Fact]
    public void SendSmsShdReturnTrue()
    {
        var fixture = new Fixture();
        
        var result = sut.SendSms(fixture.Create<string>(), fixture.Create<string>());
        result.Should().BeTrue();
    }
}

【问题讨论】:

  • 是 appSettings.json 还是 web.config ?示例文件会很有帮助。
  • 它是.net核心所以app settings.json
  • @plasteezy 任何建议的解决方案对您有用吗?

标签: c# asp.net-core-mvc moq xunit xunit.net


【解决方案1】:

另一种方法是引入一个类来表示配置的部分,然后使用IOptions 接口将其注入构造函数。

然后,您的测试变得简单,无需模拟即可配置,只需创建一个实例并将其传递给构造函数即可。

如下所示:

class SmsApiSettings
{
    public string Url { get; set; }
}

启动时注册

services.Configure<SmsApiSettings>(Configuration.GetSection("SmsApi"));

构造函数

public class ClassUnderTest
{
    private readonly SmsApiSettings _smsApiSettings;

    public ClassUnderTest(IOptions<> smsOptions)
    {
        _smsApiSettings = smsOptions.Value;
    }
}

测试

var settings = new SmsApiSettings { Url = "http://dummy.com" };
var options = Options.Create(settings);

var sut = new ClassUnderTest(options);

享受没有嘲笑的幸福生活;)

【讨论】:

  • 我喜欢这种方法,它是一种更优雅的处理方式。谢谢@Fabio
【解决方案2】:

事实是 IConfiguration 不应该被嘲笑。相反,它应该是built

通过字典

数据

var configForSmsApi = new Dictionary<string, string>
{
    {"AppSettings:SmsApi", "http://example.com"},
};

用法

var configuration = new ConfigurationBuilder()
    .AddInMemoryCollection(configForSmsApi)
    .Build();

通过json文件

数据

{
  "AppSettings": {
    "SmsApi": "http://example.com"
  }
}

用法

var configuration = new ConfigurationBuilder()
    .AddJsonFile("smsapi.json", optional: false)
    .Build();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 2010-10-19
    • 2016-09-30
    • 2019-10-06
    • 2020-10-27
    • 2012-06-01
    • 2018-12-27
    • 2019-06-16
    相关资源
    最近更新 更多