gpt4 book ai didi

visual-studio-2008 - Visual Studio 2008 - 使用 Web 配置设置进行单元测试

转载 作者:行者123 更新时间:2023-12-01 09:14:40 27 4
gpt4 key购买 nike

我的 Web 应用程序依赖于 web.config 条目为特定值(例如 FEATURE_ACTIVATED=true),那么如何测试读取此 web.config 条目的函数?

我希望避免将 web.config 条目复制到单元测试项目中的 app.config,因为同步文件需要付出额外的努力。

最佳答案

提取读取配置数据的代码,然后在测试中使用与模拟对象或模拟框架配对的依赖注入(inject)。

public interface IConfiguration
{
bool IsAwesomeFeatureActivated { get; }
}

public class Configuration: IConfiguration
{
public bool IsAwesomeFeatureActivated
{
get { /* get config value */ }
}
}

public class AwesomeFeature
{
private IConfiguration _configuration;

public AwesomeFeature(IConfiguration configuration)
{
_configuration = configuration;
}

public void ExecuteFeature()
{
if(! _configuration.IsAwesomeFeatureActivated) return;
// do awesome feature functionality
}
}

public class MockConfiguration: IConfiguration
{
private bool _isAwesomeFeatureActivated;
public void SetIsAwesomeFeatureEnabled(bool value)
{
_isAwesomeFeatureActivated = value;
}

public bool IsAwesomeFeatureActivated
{
get { return _isAwesomeFeatureActivated; }
}
}

// with mock object
[Test]
public void ExecuteFeature_WhenNotActivated_DoNothing()
{
var mockConfig = new MockConfiguration();
mockConfig.SetIsAwesomeFeatureActivated(false);
var feature = new AwesomeFeature(mockConfig);
feature.ExecuteFeature();
Assert.SomethingHere();
}

// or with Moq framework
[Test]
public void ExecuteFeature_WithActivated_DoSomething()
{
var mock = new Mock<IConfiguration>();
mock.Setup(c => c.IsAwesomeFeatureActivated).Returns(true);

var feature = new AwesomeFeature(mock.Object);
feature.ExecuteFeature();

Assert.SomethingHere();
}

关于visual-studio-2008 - Visual Studio 2008 - 使用 Web 配置设置进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2335612/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com