Nautic20 Nautic20 - 27 days ago 20
C# Question

Cannot Create LocalDB in VS 2015 Durring NUnit Test

I'm sure someone already tried this, I can't be the first one!?! I set up a test project using Visual Studio 2015, LocalDB (2014), EntityFramework 6.1.3, NUnit 3.5 and ReSharper 2016.2. Basically, I'm trying to use NUnit to run integration tests against my EntityFramework project which is connected to a LocalDB database. I have ReSharper installed on my machine and I'm using ReSharper's unit testing tools to run my NUnit unit tests (I get the exact same result using NUnit 3 console). EF is set up code-first and the app's context is set to "DropCreateDatabaseAlways" so the .mdf file should be deleted and recreated during each test.

Every time I run my unit tests, I get the same mysterious error: "System.OverflowException : Arithmetic operation resulted in an overflow." I know this is a conflict between .NET and NUnit because I set up a console app with the EXACT same settings (no unit tests) and it WORKS perfectly! The console app can create an .mdf file and I can connect to it and see it's tables using VS's LocalDB database connector.

Config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="HyperQueryEF" connectionString="Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\HyperQueryEF.mdf;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>


Model:

using System;

namespace HyperQueryEF.Model
{
public class Dealership
{
public int ID { get; set; }
public DateTime DateCreated { get; set; }
public string Name { get; set; }
}
}


DbContext:

using System.Data.Entity;

namespace HyperQueryEF.Model
{
public class HyperQueryEFContext : DbContext
{
public HyperQueryEFContext() : base("HyperQueryEF")
{
}

public void Initialize()
{
Database.SetInitializer(new DropCreateDatabaseAlways<HyperQueryEFContext>());
//Force database to initialize (Create/Migrate tables).
Database.Initialize(true);
}

public virtual DbSet<Dealership> Dealerships { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Configurations.AddFromAssembly(this.GetType().Assembly);
modelBuilder.Entity<Dealership>().ToTable("Dealership");
modelBuilder.Entity<Dealership>()
.HasKey(x => x.ID)
.Property(x => x.ID);
modelBuilder.Entity<Dealership>()
.Property(x => x.Name);

base.OnModelCreating(modelBuilder);
}
}
}


Test:

using System;
using System.IO;
using System.Reflection;
using HyperQueryEF.Model;
using NUnit.Framework;

namespace HyperQueryEF.Tests.IntegrationTests.TransactionManagerTests
{
[TestFixture]
public class When_the_app_initializes
{
private DirectoryInfo _appDataDirectory;
private HyperQueryEFContext _context;

[SetUp]
public void SetUp()
{
_appDataDirectory = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent;
AppDomain.CurrentDomain.SetData("DataDirectory", Directory.GetCurrentDirectory());
}

[Test]
public void The_database_exists_as_configured()
{
_context = new HyperQueryEFContext();
_context.Initialize();
}
}
}


(Notice I set the |DataDirectory| AppDomian setting to be consistent with a web app)

Specs:
OS: Windows 10 Pro
.NET: 4.5.2

Stack Trace:


at
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
userOptions, DbConnectionInternal& connection) at
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, TaskCompletionSource
1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection) at
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
owningConnection, TaskCompletionSource
1 retry, DbConnectionOptions
userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
connection) at
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
outerConnection, DbConnectionFactory connectionFactory,
TaskCompletionSource
1 retry, DbConnectionOptions userOptions) at
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource
1
retry) at
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource
1
retry) at System.Data.SqlClient.SqlConnection.Open() at
System.Data.Entity.Infrastructure.Interception.InternalDispatcher
1.Dispatch[TTarget,TInterceptionContext](TTarget
target, Action
2 operation, TInterceptionContext interceptionContext,
Action
3 executing, Action
3 executed) at
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection
connection, DbInterceptionContext interceptionContext) at
System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()
at
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func
1
operation) at
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection
sqlConnection, Action
1 act) at
System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable
1
commandTimeout, DbConnection sqlConnection, String
createDatabaseScript) at
System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection
connection, Nullable
1 commandTimeout, StoreItemCollection
storeItemCollection) at
System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection
connection) at
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action
mustSucceedToKeepDatabase) at
System.Data.Entity.Migrations.DbMigrator.Update(String
targetMigration) at
System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext
internalContext, Func
3 createMigrator, ObjectContext objectContext)

at System.Data.Entity.Database.Create(DatabaseExistenceState
existenceState) at
System.Data.Entity.DropCreateDatabaseAlways`1.InitializeDatabase(TContext
context) at
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action
action) at
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at HyperQueryEF.Model.HyperQueryEFContext.Initialize() in
C:\Users\agilliam\Dropbox\HyperQueryEF\Projects\HyperQueryEF.Model\HyperQueryEFContext.cs:line
15 at
HyperQueryEF.Tests.IntegrationTests.TransactionManagerTests.When_the_app_initializes.The_database_exists_as_configured()
in
C:\Users\agilliam\Dropbox\HyperQueryEF\Projects\HyperQueryEF.Tests\IntegrationTests\TransactionManagerTests.cs:line
26


Any answers or advice would be much appreciated!

Answer

Update: It just doesn't seem like Entity Framework is built to support NUnit. I built and ran the exact same test using the MSTest platform and it works. I do prefer NUnit to MSTest, but MSTest seems to get the job done just fine.

Comments