【发布时间】: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