首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在nunit测试中使用connectionstring

在nunit测试中使用connectionstring
EN

Stack Overflow用户
提问于 2010-07-02 16:39:38
回答 4查看 5.1K关注 0票数 3

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

现在我遇到了这样的问题:连接字符串没有从测试代码所在的dll的app.config中提取。

这听起来合乎逻辑,因为nunit.exe是启动应用程序,而不是测试dll (顺便说一下,当我从visual studio testframework启动测试时,它可以工作),但是我应该将连接字符串放在nunit.exe.config中吗?

我尝试在测试代码中设置它们(适用于appsettings:ConfigurationManager.AppSettings.Set("DownloadDirectory", mDir);),如下所示:ConfigurationManager.ConnectionStrings.Add(conset); (其中conset是一个ConnectionStringSettings对象),但是我得到的错误是连接字符串部分是只读的。

我应该怎么做才能在测试中使用连接字符串?

编辑:我们使用实体框架,所以我们不能将连接字符串放在appsettings中,因为它直接从节中读取,我找不到一种方法来解决这个问题。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-07-03 01:17:32

使用反射,您可以(在内存中)更改Configuration.ConnectionStringsconnectionName,的值,在这种情况下,您可能会在SetUp或TestFixtureSetUp中执行此操作。参见http://david.gardiner.net.au/2008/09/programmatically-setting.html

代码语言:javascript
运行
复制
// 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;
票数 6
EN

Stack Overflow用户

发布于 2013-09-24 17:49:01

我知道这不是你要找的答案,但这是我用来解决你同样问题的答案:

您至少可以在EF5和EF4.3中修改您的DbContext实现,并添加接受硬编码连接字符串的构造函数,如下所示:

代码语言:javascript
运行
复制
    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 
    } 

每次重新生成上下文时,您都必须粘贴此内容,但我认为这是值得的。连接字符串必须是使用元数据和所有内容格式化的实体框架,但您将能够弄清楚它。把它放在某个地方,这样你就可以在需要的时候把它粘贴进去。

票数 2
EN

Stack Overflow用户

发布于 2010-07-02 16:41:52

你可以从ConfigurationManager.AppSettings中读取连接字符串值,是的,它是只读的。您可以在App.Config中更改它。如果你想改变连接字符串中的一些值,对于ex,你可以在代码中改变你的dataContext.URL或者任何你想要的编码属性。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3164251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档