Using a connector string in a nunit test

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

Now I am experiencing a problem that the connection string is not retrieved from app.config from the dll where the test code is located.

This sounds logical because nunit.exe is a starting application, not a test dll (it worked when I ran tests from the visual studio testframework, by the way), but should I set the line lines to nunit. exe.config?

I tried to install them in the test code (works for appsettings: ConfigurationManager.AppSettings.Set("DownloadDirectory", mDir);)as follows: ConfigurationManager.ConnectionStrings.Add(conset);(where consetis the object ConnectionStringSettings), but then I get an error message that the connectionstrings section is read-only.

What should I do to use string values ​​in my test?

EDIT: we use an entity structure, so we cannot put the connection string in the application settings, because it reads directly from the section, I could not find a way around this behavior.

+3
source share
4 answers

Using reflection, you can (in memory) change your Configuration.ConnectionStrings [connectionName] value, which in your case you are likely to do in SetUp or, possibly, in 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;
+6
source

, , , , :

, , 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 
    } 

, , . , , . -, .

+2

ConfigurationManager.AppSettings, , . App.Config. , ex URL, dataContext.URL , .

+1

, . .

0

Source: https://habr.com/ru/post/1752787/


All Articles