在NUnit测试

问题描述:

我们使用nunit.exe应用程序中使用ConnectionString,以运行我们的(集成)测试在NUnit测试

现在我遇到ConnectionString中未从app.config中从DLL拿起问题,其中的测试代码是在。

这听起来很合逻辑,因为nunit.exe是开始的应用程序,而不是测试DLL(它曾经工作,当我从Visual Studio的测试框架开始测试的方式),但我应该把nunit.exe.config中的连接字符串?

我试图在testcode(设置它们的工作原理为的AppSettings:ConfigurationManager.AppSettings.Set("DownloadDirectory", mDir);)这样的: ConfigurationManager.ConnectionStrings.Add(conset);(其中consetConnectionStringSettings对象),但后来我得到错误的connectionStrings节是只读的

什么。我应该如何在我的测试中使用连接字符串?

编辑: 我们使用实体框架,所以我们不能将连接字符串放在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; 
+0

如果这是从DLL运行的,那么将不存在现有的连接字符串。在这种情况下,你需要添加一个新的连接字符串。 – Nathan 2011-06-14 13:58:30

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

+0

我们使用实体框架,因此我们无法将连接字符串置于appsettings中,因为它从节中读取。 – Michel 2010-07-02 08:51:17

我认为单元测试可能很容易。您可以直接将连接字符串作为硬编码字符串放入测试类中。在简单的单元测试中,你测试有限的逻辑范围并且不关心输入参数的真实性

+0

我们使用实体框架,所以我们不能将连接字符串放在appsettings中,因为它从节中读取 – Michel 2010-07-02 08:51:46

我知道这是不是你正在寻找的答案,但它是一个我用于解决您的同一个问题:

您可以修改,在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 
    } 

你将不得不粘贴每次重新生成语境时间这个东西,但恕我直言这是值得冒这个险。连接字符串必须使用元数据和所有内容格式化为实体框架,但您可以将其弄清楚。只要将它保存在某个地方,以便在需要时粘贴它。