Skip to content

Commit

Permalink
Adding support for using a test connection string.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jaben committed Feb 18, 2024
1 parent a3289cd commit 73174a3
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 6 deletions.
30 changes: 30 additions & 0 deletions TrackableEntities.EF.Core.Tests/Helpers/DbContextOptionsHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;

using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace TrackableEntities.EF.Core.Tests.Helpers
{
public static class DbContextOptionsHelper
{
public static DbContextOptions<TContext> GetContextOptions<TContext>(string initialCatalog)
where TContext : DbContext
{
// default connection string for tests 'LocalDb'
var connectionString =
@"Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=FamilyTest; Integrated Security=True; MultipleActiveResultSets=True";

if (Environment.GetEnvironmentVariable("ConnectionString") != null)
{
// LocalDb isn't supported in Linux. To support running tests, allow env variable for conn string
connectionString = Environment.GetEnvironmentVariable("ConnectionString");
}

var builder = new SqlConnectionStringBuilder(connectionString) { InitialCatalog = initialCatalog };

return new DbContextOptionsBuilder<TContext>()
.UseSqlServer(builder.ConnectionString)
.Options;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ public void Initialize(bool useInMemory = true, Action seedData = null)
}
else
{
_options = new DbContextOptionsBuilder<FamilyDbContext>()
.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB; Initial Catelog=FamilyTest; Integrated Security=True; MultipleActiveResultSets=True")
.Options;
_options = DbContextOptionsHelper.GetContextOptions<FamilyDbContext>("FamilyTest");
}
_context = new FamilyDbContext(_options);
_context.Database.EnsureCreated();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ public void Initialize(bool useInMemory = true, Action seedData = null)
}
else
{
_options = new DbContextOptionsBuilder<NorthwindDbContext>()
.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=NorthwindTest; Integrated Security=True; MultipleActiveResultSets=True")
.Options;
_options = DbContextOptionsHelper.GetContextOptions<NorthwindDbContext>("NorthwindTest");
}
_context = new NorthwindDbContext(_options);
_context.Database.EnsureCreated(); // If login error, manually create NorthwindTest database
Expand Down

0 comments on commit 73174a3

Please sign in to comment.