c# - 组织执行测试的方法 - C#

标签 c# unit-testing testing class-design

我现在有一个类,在这个类中它有 15 个左右的私有(private)方法,这些方法在定时器运行的循环中执行某些任务。其中一些方法调用数据库,而另一些则不调用。

问题是......我如何安排这些以便我可以设置类以便我可以伪造 repo 或执行过程?

这是我现在的简化版本。

public class Manager : IManager
{
    System.Timers.Timer tm;
    private bool runningAsService;
    private List<Database> Databases = new List<Database>();
    private LogClass Log;

    public Manager(bool RunningAsService, LogClass log)
    {
        runningAsService = RunningAsService;
        Log = log;

        tm = new System.Timers.Timer(Settings.idle_time * 1000);
        tm.Elapsed += new System.Timers.ElapsedEventHandler(delegate { PerformDuties(); });
    }

    public void Start()
    {
        tm.Start();
        PerformDuties();
    }

    private PerformDuties()
    {
        //Call the other 10-15 private methods to perform all the tasks needed.
    }
}

最佳答案

每个 Db 操作最终都将成为 CRUD 操作之一。因此,您可以从您的数据库类中提取出 IDatabase,换句话说,将您的数据访问层抽象出来,像这样:

public interface IDatabase<T> 
{
     T CreateItem();
     T ReadItem(Id id);
     bool UpdateItem(T item);
     bool DeleteItem(T item)
}

并使用像 Castle Windsor 这样的 DI 框架使用依赖注入(inject)注入(inject)数据库列表, Spring.NET等通过 Setter 或 Ctor 注入(inject)到你的 Manager

希望这是有道理的.. :)

关于c# - 组织执行测试的方法 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/896396/

相关文章:

c# - 将视频上传到特定 channel /Youtube

javascript - Mocha 模拟导入变量

android - 如何为安卓做跨应用自动化测试

c# - 我在一个 View 中混合了创建 View 和索引 View 代码。那么,如何通过 asp.net MVC4 中的 View 从数据库中检索数据?

c# - 如何使用angularjs在c#中调用API

java - 我是否需要测试接口(interface)的每个实现来测试接口(interface)?

unit-testing - MediatorLiveData 在 JUnit 测试中不起作用?

javascript - 使用 Cypress 验证元素是否在视口(viewport)内

angular - 如何在 Karma 中运行特定的测试文件? ( Angular 4+)

c# - 在 ASP.NET MVC3 中正确使用 TempData?