Friday, March 1, 2013

How to REALLY read from App.Config in a C# unit test project.

I have never been able to get this to work when revisiting it. I can't tell what I was thinking. Whatever. Here is the real way to do this and it is very easy:

using System.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject
{
   [TestClass]
   public class UnitTest
   {
      [TestMethod]
      public void TestMethod()
      {
         AppSettingsReader appSettingsReader = new AppSettingsReader();
         string baz = (string)appSettingsReader.GetValue("foo", typeof (string));
         Assert.AreEqual(baz, "bar");
      }
   }
}

 
 

Again: The build action on the App.config file needs to be "Content" and the "Copy to Output Directory" setting needs to be "Copy if newer." More: App.config should be configured as you might expect to accomodate appSettings. Mine looks like this:

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

No comments:

Post a Comment