HO到单元测试静态类,该类具有读取不同配置值的方法

发布于 2025-02-12 02:26:05 字数 482 浏览 2 评论 0原文

public static class Settings
{
    public static bool IsFlagEnabled()
    {
        bool isFlag;
        bool.TryParse(ConfigurationManager.AppSettings["isFlag"], out isFlag);
        return isFlag;
    }
 }

//单元测试

     [Fact]
    public void isFlagEnabled()
      {
        // act
        var isFlagEnabled = Settings.IsFlagEnabled();
        // assert
        Assert.True(isFlagEnabled);
    }

//单元测试始终返回false for配置值

public static class Settings
{
    public static bool IsFlagEnabled()
    {
        bool isFlag;
        bool.TryParse(ConfigurationManager.AppSettings["isFlag"], out isFlag);
        return isFlag;
    }
 }

// Unit Test

     [Fact]
    public void isFlagEnabled()
      {
        // act
        var isFlagEnabled = Settings.IsFlagEnabled();
        // assert
        Assert.True(isFlagEnabled);
    }

//The unit tests always returns false for the config value

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悲喜皆因你 2025-02-19 02:26:05

您的单位测试实际试图测试什么?

  1. 如果bool.tryparse按预期工作?
  2. 如果ConfigurationManager.AppSetting按预期工作并加载配置文件?
  3. 如果实际配置文件具有可以解析为布尔值的“ ISFLAG”值?

在第一种情况下,您可以直接测试bool.tryparse,或进行扩展,bool asbool(此名称valuecollection self,string键)...提供更方便的访问 +解析。

第二种情况可能不是很有意义,因为该功能是由框架提供的,但是应该可以设置构建,以便为单位测试提供配置文件,并带有一些测试数据。

在第三种情况下,您需要一个实际的配置文件来加载,因此测试可能会更麻烦,但是如果您可以检测到某人编写“ TROE”而不是“ True”,也可能会提供更多的价值。

请记住,单位测试应提供。根据我的经验,对非常简单的方法或涉及大量依赖的方法的单位测试往往比依赖关系的高度复杂方法提供的价值较低。我建议您反对教条规则,例如“所有方法必须进行单位测试”。

What is your unit test actually trying to test?

  1. If bool.TryParse works as intended?
  2. If ConfigurationManager.AppSetting works as intended and loads the config file?
  3. If the actual configuration file has a "isFlag" value that can be parsed as a boolean?

In the first case you could just test bool.TryParse directly, or make an extension, bool AsBool(this NameValueCollection self, string key) ... to provide a more convenient access + parsing.

The second case would probably not be very meaningful since the functionality is provided by the framework, but it should be possible to setup the build to provide the unit test with a configuration file with some test data.

In the third case you need an actual config file to load, so it will probably be more cumbersome to test, but might also give more value if you can detect that someone wrote "troe" instead of "true".

Keep in mind that unit tests should provide value. In my experience unit testing of very simple methods, or methods involving lots of dependencies, tend to provide lower value than highly complex methods with few dependencies. I would recommend against dogmatic rules like "all methods must be unit tested".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文