我想自动测试http://localhost/api.ashx。
api.ashx从web.config读取配置并采取不同的行动。
例如,一个键是AllowDuplicatedQueryParameter。如果web.config有
<appSettings>
<add key="AllowDuplicatedQueryParameter" value="false" />
</appSettings>
请求http://localhost/api.ashx?name=hello&name=world会抛出错误。
如何进行测试不同配置的自动化测试,即AllowDuplicatedQueryParameter = true和AllowDuplicatedQueryParameter = false?
答案 0 :(得分:1)
这取决于您想要做什么样的自动化测试。在这种情况下,对应用程序的进程内版本进行单元测试或集成测试似乎是有意义的。
在这些情况下,您最好的选择是将配置的读取抽象为可以模拟的类。例如,假设您更改的配置位于AppSettings中,您可能会执行与此类似的操作
public interface IConfigurationWrapper
{
string GetAppSetting(string key);
}
public class ConfigurationWrapper : IConfigurationWrapper
{
public string GetAppSetting(string key)
{
return ConfigurationManager.AppSettings[key]
}
}
您的组件应依赖于
IConfigurationWrapper
,并在需要访问配置以确定行为时使用它。在您的测试中,您可以使用像Moq或NSubstitute这样的模拟库,或者滚动您自己的IConfigurationWrapper
存根实现,并使用它来控制被测系统的行为,如下所示:
public class MyThingDoer
{
public MyThingDoer(IConfigurationWrapper config)
{
_config = config
}
public string SaySomething()
{
var thingToSay = _config.GetAppSetting("ThingToSay");
return thingToSay;
}
}
然后在你的测试中
[Fact]
public void ThingDoerSaysWhatConfigTellsItToSay()
{
var configWrapper = new FakeConfigWrapper(thingToSay:"Hello");
var doer = new MyThingDoer(configWrapper);
Assert.Equal("Hello", doer.SaySomething());
}
显然,这是一个玩具的例子,但它应该得到基本的想法。写一个关于外部依赖的抽象,然后存根依赖。