数据驱动单元测试破坏实体框架连接

时间:2015-09-18 17:56:16

标签: entity-framework unit-testing data-driven-tests

我有一个使用实体框架的应用程序。我正在编写一个单元测试,我希望从CSV文件中使用数据驱动测试。

但是,当我运行测试时,出现无法加载sqlserver提供程序的错误:

  

初始化方法UnitTest.CalculationTest.MyTestInitialize抛出   例外。 System.InvalidOperationException:   System.InvalidOperationException:实体框架提供程序类型   “System.Data.Entity.SqlServer.SqlProviderServices,   EntityFramework.SqlServer'在应用程序配置文件中注册   对于具有不变名称'System.Data.SqlClient'的ADO.NET提供程序   无法加载。确保程序集限定名称   已使用,并且程序集可供正在运行的应用程序使用。

  1. 如果我删除了数据驱动的方面,只测试一个值,那么测试就可以了。
  2. 如果我只是使用数据驱动方面并删除实体框架内容,那么测试就可以了。
  3. 所以,只有当我尝试使用数据驱动的测试同时激活实体框架时才会出现错误。那么,我在哪里错了?

    这是我的测试方法:

    [TestMethod, TestCategory("Calculations")
    , DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV"
               , "ConvertedMeanProfileDepth.csv", "ConvertedMeanProfileDepth#csv"
               , Microsoft.VisualStudio.TestTools.UnitTesting.DataAccessMethod.Sequential)
    , DeploymentItem("ConvertedMeanProfileDepth.csv")]
    public void ConvertedMeanProfileDepthTest()
    {
        ConvertedMeanProfileDepth target = new ConvertedMeanProfileDepth();
        Decimal mpd = decimal.Parse(this.TestContext.DataRow["mpd"].ToString());
        Decimal expected = decimal.Parse(this.TestContext.DataRow["converted"].ToString());
        Decimal actual;
        actual = target.Calculate(mpd);
        Assert.AreEqual(expected, actual);
    }
    

1 个答案:

答案 0 :(得分:2)

所以我最终设法解决了这个问题。为了将来参考,以下是解决方案:

Rob Lang的帖子Entity Framework upgrade to 6 configuration and nuget magic让我想起了这个问题:

  

当无法为a中引用的DLL加载类型时   项目,它通常意味着它没有被复制到输出   bin /目录。当您未使用引用的类型时   库,它不会被复制。

当你在测试中使用部署项时,这会引起它的丑陋头脑。如果在测试中使用部署项,则会将所有必需二进制文件复制到部署目录。问题是,如果您使用动态加载的项目,那么测试套件不知道它必须复制这些项目。

使用Entity Framework,这意味着您的提供程序不会被复制到部署位置,并且您将根据我的问题收到错误。

要解决此问题,只需确保您的实体框架提供程序也标记为部署项目。

因此,请注意在我的测试属性中包含 DeploymentItem(@" EntityFramework.SqlServer.dll")。一切都在这里完美运作:

 [TestMethod, TestCategory("Calculations")
    , DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV"
               , "ConvertedMeanProfileDepth.csv", "ConvertedMeanProfileDepth#csv"
               , Microsoft.VisualStudio.TestTools.UnitTesting.DataAccessMethod.Sequential)
    , DeploymentItem("ConvertedMeanProfileDepth.csv")
    , DeploymentItem(@"EntityFramework.SqlServer.dll")]
    public void ConvertedMeanProfileDepthTest()
    {
        ConvertedMeanProfileDepth target = new ConvertedMeanProfileDepth();
        Decimal mpd = decimal.Parse(this.TestContext.DataRow["mpd"].ToString());
        Decimal expected = decimal.Parse(this.TestContext.DataRow["converted"].ToString());
        Decimal actual;
        actual = target.Calculate(mpd);
        Assert.AreEqual(expected, actual);
    }