[英]Using the connectionstring in an nunit test
我们使用nunit.exe应用程序来运行我们的(集成)测试
现在我遇到的问题是,从测试代码所在的dll中的app.config中没有获取connectionstring。
这听起来合乎逻辑,因为nunit.exe是启动应用程序,而不是测试dll(它曾经在我从Visual Studio testframework开始测试的时候工作)但是我应该把连接字符串放在nunit.exe.config中?
我尝试在testcode中设置它们(适用于appsettings: ConfigurationManager.AppSettings.Set("DownloadDirectory", mDir);)
如下所示: ConfigurationManager.ConnectionStrings.Add(conset);
(其中conset
是一个ConnectionStringSettings
对象),但后来我得到了connectiontrings部分只读的错误。
我该如何在测试中使用连接线?
编辑:我们使用实体框架,因此我们不能将连接字符串放在appsettings中,因为它直接从该部分读取,我找不到解决此问题的方法。
使用反射,您可以(在内存中)更改Configuration.ConnectionStrings [connectionName]的值,在您的情况下,您可能会在SetUp或TestFixtureSetUp中执行此操作。 见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;
我意识到这不是你正在寻找的答案,但它是我用来解决同样问题的答案:
您至少可以在EF5和EF4.3中修改DbContext实现并添加一个接受硬编码连接字符串的构造函数,例如:
public partial class MyContext : DbContext
{
public MyContext() : base("name=MyContext")
{
}
// --- Here is the new thing:
public MyContext(string entityConnectionString) : base(entityConnectionString)
{
}
// --- New thing ends here
// .... the rest of the dbcontext implementation follows below
}
你必须在每次重新生成上下文时粘贴这个东西,但恕我直言,这是值得的麻烦。 连接字符串必须是使用您的元数据和所有内容格式化的实体框架,但您将能够弄清楚它。 只需将它放在某处,这样您就可以在必要时粘贴它。
您可以从ConfigurationManager.AppSettings读取连接字符串值,是的,它是只读的。 您可以在App.Config中更改它。 如果要更改连接字符串中的某些值,对于ex URL,可以在代码中更改dataContext.URL或编码所需的任何属性。
我认为对于单元测试来说可能要容易得多。 您可以将连接字符串直接作为硬编码字符串放入测试类中。 在简单的单元测试中,您测试有限的逻辑范围,而不是真正关注输入参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.