Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the connectionstring in an nunit test

we use the nunit.exe application to run our (integration)test

Now i experience the problem that the connectionstring is not picked up from the app.config from the dll where the testcode is in.

That sounds logical because the nunit.exe is the starting app and not the test dll (it used to work when i started the tests from the visual studio testframework by the way), but should i put the connectionstrings in the nunit.exe.config?

I tried setting them in the testcode (works for the appsettings : ConfigurationManager.AppSettings.Set("DownloadDirectory", mDir);) like this: ConfigurationManager.ConnectionStrings.Add(conset); (where conset is a ConnectionStringSettings object), but then i get the error that the connectionstrings section is readonly.

What should i do to use the connectionstrings in my test?

EDIT: we use the entity framework so we can't put the connectionstring in the appsettings because it reads from the section directly, i couldn't find a way to work around this behaviour.

like image 972
Michel Avatar asked Oct 23 '25 15:10

Michel


1 Answers

Using reflection, you can (in memory) change your value of the Configuration.ConnectionStrings[connectionName], which in your case you would probably do in SetUp or perhaps TestFixtureSetUp. See http://david.gardiner.net.au/2008/09/programmatically-setting.html.

// Back up the existing connection string
ConnectionStringSettings connStringSettings = ConfigurationManager.ConnectionStrings[connectionName];
string oldConnectionString = connStringSettings.ConnectionString;

// Override the IsReadOnly method on the ConnectionStringsSection.
// This is something of a hack, but will work as long as Microsoft doesn't change the
// internals of the ConfigurationElement class.
FieldInfo fi = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(connStringSettings, false);

// Set the new connection string value
connStringSettings.ConnectionString = connectionStringNeededForNUnitTest;
like image 100
Eric Pohl Avatar answered Oct 25 '25 05:10

Eric Pohl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!