在NUnit测试使用的ConnectionString测试、NUnit、ConnectionString

2023-09-05 23:36:57 作者:记忆,格式化

我们使用nunit.exe应用程序来运行我们的(集成)测试

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

现在我遇到ConnectionString中未接走在app.config从DLL当测试code是问题。

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

这听起来合乎逻辑,因为nunit.exe是启动应用程序,而不是测试dll(以前,当我开始从Visual Studio testframework顺便测试工作),但我应该把的ConnectionStrings在NUnit的。 exe.config?

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?

我试着将它们设置在测试code(工程,为的AppSettings: ConfigurationManager.AppSettings.Set(DownloadDirectory,MDIR);)是这样的: ConfigurationManager.ConnectionStrings.Add(conset); (其中 conset ConnectionStringSettings 对象),但后来我得到错误的connectionStrings节是只读的。

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.

我应该怎么做才能使用的ConnectionStrings在我的测试?

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

编辑: 我们使用实体框架,所以我们不能把ConnectionString中的AppSettings的,因为它直接从部分读取,我无法找到一个方法来解决此问题。

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.

推荐答案

使用反射,你可以(在内存中)改变你的Configuration.ConnectionStrings [connectionName中],而你的情况,你可能会做在安装程序中或者价值TestFixtureSetUp。请参阅http://david.gardiner.net.au/2008/09/programmatically-setting.html.

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;