1

I want to understand a proper way of handling the scenario below

I have C# Solution which has two projects One project is HelloWorld and another project is TestHelloWorld

HelloWorld project read the config using ConfigurationManager.AppSettings["Message"].ToString()

And TestHelloWorld project is the NUnit project to test the HelloWorld project.

When the job being run from NUnit, the code of reading config is not working. Because it tried to read config from TestHelloWorld.config instead of HelloWorld.exe.config.

Can someone please provide some good practice of handling this.

I attached a graphic of my source code and also put the code below, appreciate people if you can download the code and have a try.

ThanksSource Code Image

Program.cs code as below

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Configuration;

    namespace HelloWorld
    {
        class Program
        {
            static void Main(string[] args)
            {
                WordToSay wts = new WordToSay();
                Console.WriteLine(wts.WordText());
                Console.ReadLine();
            }
        }

        public class WordToSay
        { 
            public string WordText()
            {
                return ConfigurationManager.AppSettings["Message"].ToString();
            }
        }
    }

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings >
        <add key ="Message" value ="Hello"/> 
   </appSettings>
</configuration>

Class1.cs code as below

    using System;
    using System.Collections.Generic;
    using System.Text;
    using NUnit.Framework;
    using HelloWorld ;

    namespace TestHelloWorld
    {
        [TestFixture]
        public class Class1
        {
            [Test]
            public void TestHello()
            {
                WordToSay wts = new WordToSay();
                StringAssert.AreEqualIgnoringCase("Hello", wts.WordText ()); 
            }
        }
    }
yangbin990
  • 83
  • 7
  • 1
    As an aside, this isn't a very good unit test since you're not testing any logic, but are essentially trying to test the functionality of the `ConfigurationManager` which you can assume Microsoft is already doing. – Steve Feb 11 '16 at 05:58

1 Answers1

0

If your unit tests are designed to test the code, then don't depend on the config file at all. Extract your dependency out of your classes and use dependency injection to inject the data in. That way, you can stub your configuration class.

Alternatively, just add an app.config file to your unit testing project that contains the relevant information.

EDIT: You can also look over this post Reload app.config with nunit

Community
  • 1
  • 1
Mainul
  • 879
  • 7
  • 10