gpt4 book ai didi

c# - Nunit、Asp.net MVC 4、Sql Server CE 4、错误提供程序

转载 作者:太空宇宙 更新时间:2023-11-03 16:32:38 25 4
gpt4 key购买 nike

  • 我创建了一个简单的 Asp.net MVC 4 应用程序
  • 我使用 visula studio 2010 扩展创建了 NUnit 测试项目
  • 我添加了几个 Controller (带有模型和 View )并且网站运行良好。它适用于 SQL Server CE

现在我需要测试一个 Controller 。我写了这个简单的类:

namespace SkateboardShop.Tests.Controllers
{
[TestFixture]
class BrandControllerTest
{

[Test]
public void TestDetailsView()
{

var controller = new BrandController();
var result = controller.Details(2) as ViewResult;
Assert.AreEqual("Details", result.ViewName);

}

}
}

当我运行这个测试时,NUnit 返回这个错误:

SkateboardShop.Tests.Controllers.BrandControllerTest.TestDetailsView: System.Data.ProviderIncompatibleException : An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct. ----> System.Data.ProviderIncompatibleException : The provider did not return a ProviderManifestToken string. ----> System.Data.SqlClient.SqlException : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

当然,测试项目从哪里获取数据提供者信息?我将连接字符串添加到(测试项目的)app.config 文件中:

<connectionStrings>
<add name="SkateboardEntities" connectionString="Data Source=d:\Basic\project\asp\SkateboardShop\SkateboardShop\App_Data\SkateboardShop.sdf" providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>

但无事可做。由于我是 MVC 和 NUnit 的新手,所以我首先要问的是,单元测试是否应该测试真实的数据库数据,如果这是一个好方法,如何去做。

谢谢。

最佳答案

在我看来——您应该有一个用于测试的模拟存储库/持久层。以这种方式 - 您可以获得可预测的结果集来处理和编写测试。

这方面的一个例子可能是您的 Controller 接受一个存储库实例,代码如下:

public class BrandController{
public BrandController(IBrandRepository repository){...}
}

您可以使用任何 DI + Mock 框架注入(inject) IBrandRepository 进行单元测试

但是,在某些情况下,模拟是不够的,您确实需要一个物理数据库来进行测试。

在这种情况下,我会建议有一个具有相同结构的测试数据库,但可以根据单元测试的需要重新播种/初始化测试数据。

在这种情况下,您可以将您的配置文件指向测试数据库以进行测试,并使用某种脚本或 DbInitializer 将数据库初始化回原始状态等。

HTH.

关于c# - Nunit、Asp.net MVC 4、Sql Server CE 4、错误提供程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10353818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com