1

In my EntityFrame work application, I am connecting to a database for certain database operations. But in order to unit test my application, I don't want to be hitting the actual database file so I have added a sample database (copy of actual database).

I want to connect this database when my unit tests are running. Here is my code for connection string.

public string ConnectionString
        {
            get
            {
                if (IsTesting)
                {
                    var executingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    var attachDbFilename = Path.Combine(executingDirectory, UnitTestBase.DatabaseFileName);
                    EntityBuilder.ProviderConnectionString = string.Format(CultureInfo.InvariantCulture, "data source= {0};AttachDbFilename={1};UID={2};PWD={3};MultipleActiveResultSets=True", HostName, attachDbFilename, "sa", "mySaPassword123");                        
                }
                else
                    EntityBuilder.ProviderConnectionString = string.Format(CultureInfo.InvariantCulture, "data source= {0};initial catalog={1};integrated security=True;MultipleActiveResultSets=True", HostName, CatalogName);
                return EntityBuilder.ToString();
            }
        }

Which basically means that in case of Unit testing I am trying to attach a different (sample) db. But I am unable to figure out the connection string in this base. How can I write the connection string for my SQL Server (.mdf) database in this case?

halfer
  • 19,824
  • 17
  • 99
  • 186
WAQ
  • 2,556
  • 6
  • 45
  • 86
  • 2
    Check this link: http://stackoverflow.com/questions/8926512/how-do-i-connect-to-an-mdf-database-file – kamil-mrzyglod Jun 08 '15 at 11:45
  • 2
    In my experience, trying to hit an actual database during unit tests only leads to maintenance problems. If at all possible, I would go with a mocking framework. https://msdn.microsoft.com/en-us/data/dn314429.aspx – Wyatt Earp Jun 08 '15 at 11:55

0 Answers0