NUnit 测试期间无法在 VS 2015 中创建 LocalDB

Cannot Create LocalDB in VS 2015 During NUnit Test

我确定有人已经尝试过了,我不能成为第一个!?!我使用 Visual Studio 2015、LocalDB (2014)、EntityFramework 6.1.3、NUnit 3.5 和 ReSharper 2016.2 设置了一个测试项目。基本上,我正在尝试使用 NUnit 对连接到 LocalDB 数据库的 EntityFramework 项目进行 运行 集成测试。我在我的机器上安装了 ReSharper,我正在使用 ReSharper 的单元测试工具 运行 我的 NUnit 单元测试(我使用 NUnit 3 控制台得到完全相同的结果)。 EF 设置为代码优先,应用程序的上下文设置为 "DropCreateDatabaseAlways",因此应在每次测试期间删除并重新创建 .mdf 文件。

每次我 运行 我的单元测试,我都会得到同样的神秘错误:“System.OverflowException:算术运算导致溢出。”我知道这是 .NET 和 NUnit 之间的冲突,因为我使用完全相同的设置(没有单元测试)设置了一个控制台应用程序并且它工作得很好!控制台应用程序可以创建一个 .mdf 文件,我可以连接到它并使用 VS 的 LocalDB 数据库连接器查看它的表。

配置:

<?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>

型号:

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);
        }
    }
}

测试:

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();
        }
    }
}

(注意我将 |DataDirectory| AppDomian 设置设置为与网络应用一致)

规格: OS: Windows 10 专业版 .NET:4.5.2

堆栈跟踪:

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, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.Open() at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action2 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 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](Func1 operation) at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act) at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 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, Func3 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

更新:Entity Framework 似乎并不支持 NUnit。我使用 MSTest 平台构建并 运行 完全相同的测试并且它有效。我确实更喜欢 NUnit 而不是 MSTest,但 MSTest 似乎可以很好地完成工作。