unit-testing - 数据访问、单元测试、依赖注入(inject)

标签 unit-testing dependency-injection data-access

我最近的任务是创建一个简单的实用程序,该实用程序允许将具有特殊格式的文件中的数据导入数据库。我用几个类实现了控制台应用程序(程序类与业务逻辑类一起操作,业务逻辑类又与数据访问类一起操作)。一切正常,但现在我正在考虑创建一些单元测试和重构应用程序(我之前没有创建过真正的单元测试,很久以前只是一堆集成测试,所以我相信这个应用程序是练习的完美领域) .

所以,问题来了:数据访问类已经变成静态的,这不允许模拟它,因此会创建真正的单元测试。为了解决这个问题,我需要创建一个接口(interface)并在数据访问类中实现它。此外,我将不得不向业务逻辑类添加一个构造函数,该类将接受该接口(interface)类型的参数。所以这意味着我最终将在应用程序 Main() 方法中创建数据访问类,并且有些东西告诉我这不是最好的方法(入口点应该知道一些数据访问的事情真的可以吗?如果链是更长的时间还是应该有几个链条?)。我知道我可以使用一些 IoC 容器,但我认为这对于使用容器来说太简单了。

谢谢!

最佳答案

I need to create an interface and implement it in the data access class. Also I will have to add a constructor to the business logic class that will accept parameter of that interface type. So this means that I will end up creating data access class in the application Main() method and something tells me this not the best approach (is it really ok that the entry point should know about some data access things? what if the chain is much longer or there should be several chains?)



相反!这是最好的方法,至少从可测试性的角度来看。

使您的业务逻辑层可测试的唯一方法是通过完全按照您的计划将其与数据访问层隔离开来。

您的顶级应用程序是停止工作的地方——它是唯一需要知 Prop 体数据访问类是什么的组件。

如果链更长或有多个链,那没什么大不了的(尽管如果失控,您可能需要考虑折叠一些应用程序层)。考虑 Model-View-Presenter 中的这个潜在代码应用程序的View ,其中 Presenter依赖于 CustomerService ,它依赖于 Repository以及对 AccountingService 的依赖(这也取决于 Repository ):
public CustomerView() {
    IRespository       repository        = new ConcreteRepository();
    IAccountingService accountingService = new ConcreteAccountingService(repository);
    ICustomerService   customerService   = new ConcreteCustomerService(accountingService, repository)
    this._Presenter = new CustomerPresenter(customerService);
}

最后,如果您不想使用依赖注入(inject)容器(尽管其中一些非常轻量级),则无需使用依赖注入(inject)容器 - 手动依赖注入(inject)工作正常,直到您开始在整个地方重复自己(或发现您想要配置运行时的依赖项)。

关于unit-testing - 数据访问、单元测试、依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1454859/

相关文章:

sql-server - 存储过程中可以有可选的 OUTPUT 参数吗?

c++ - 将测试代码构建为库还是可执行文件?

asp.net-mvc - DAL -> BLL <- GUI + 组合根。如何设置 DI 绑定(bind)?

node.js - Mocha 重试不起作用

c# - 使用 MVVMLight 时如何设置 Web API DependencyResolver

c# - 在 ASP.NET Core 中启动 BackgroundService 的正确方法

sql-server - 需要帮助锁定我的 SQL Server 代码

c# - Nhibernate:谁负责非 web 应用程序中的事务管理

c++ - 单元测试一个类是不可复制的,以及其他编译时属性

php - 在 lumen 5.5 中测试文件上传