【问题标题】:How to test a web service with different configurations? [duplicate]如何测试具有不同配置的 Web 服务? [复制]
【发布时间】:2017-06-07 17:45:53
【问题描述】:

我想自动测试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 时?

【问题讨论】:

    标签: c# unit-testing integration-testing system-testing


    【解决方案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());
    }
    

    显然这是一个玩具示例,但它应该了解基本概念。围绕外部依赖编写一个抽象,然后存根依赖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 2012-03-31
      • 1970-01-01
      相关资源
      最近更新 更多