如何使用 Moq 模拟 IConfiguration? 数据用法数据用法

问题描述

如何在我的单元测试中模拟这样的代码。我在 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();
    }
}

解决方法

替代方法 tp 引入一个类来表示配置的部分,然后使用 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);

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

,

事实是 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();

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...