1
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

Jen
  • 87
  • 7
  • 1
    you have to inject or mock "Configuration" for Unittest. – CodingMytra Jul 01 '22 at 08:22
  • Does this answer your question? [How to mock ConfigurationManager.AppSettings with moq](https://stackoverflow.com/questions/9486087/how-to-mock-configurationmanager-appsettings-with-moq) – Markus Jul 01 '22 at 08:24
  • In addition to the duplicate that should help for the concrete problem, I'd recommend to make the static class non-static and inject the dependencies so that they can be replaced during the unit test. Static classes always seem easy at first, in the long run you often replace it by a non-static class structure in most cases (at least from my experience). – Markus Jul 01 '22 at 08:27

1 Answers1

0

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".

JonasH
  • 28,608
  • 2
  • 10
  • 23