c# - 如何对使用数据库访问的静态方法进行单元测试?

标签 c# unit-testing testing linq-to-sql

这是示例静态方法,例如

public static void UpdateSchedule(int selectedScheduleId)
        {
            using (var dc = new MyDataContext())
            {
                var selectedSchedule = dc.Schedules.SingleOrDefault(p => p.ScheduleId == selectedScheduleId)
                if selectedSchedule != null)
                {
                    selectedSchedule.Name = name;
                    //and update other properties...
                }
                dc.SubmitChanges();
            }
        }

那么测试此类方法的正确方法是什么?有没有办法避免调用 new MyDataContext(),因为它可能会增加单元测试的执行时间。

另外,我在VS2012中使用MsTest测试框架。

最佳答案

静态函数干扰测试主要是因为它们:

  1. 很难(有时不可能)从消费者内部进行替代
  2. 往往有“隐藏”的依赖关系

由于您想测试函数本身,因此数字 1 不是问题。然而,数字 2 是有问题的,因为静态函数是 tightly coupledMyDataContext 类。

如果您想在没有 MyDataContext 的情况下测试静态函数(即隔离),您需要 introduce a code seam 。这需要一些重构工作,但我们可以相当轻松地完成。

考虑一下您是否有以下附加方法:

    public static void UpdateScheduleWithContext(int selectedScheduleId, IDataContext dc)
    {
        var selectedSchedule = dc.Schedules.SingleOrDefault(p => p.ScheduleId == selectedScheduleId)
        if selectedSchedule != null)
        {
            selectedSchedule.Name = name;
            //and update other properties...
        }
        dc.SubmitChanges();
    }

这个新函数使使用者(即测试)能够为数据上下文提供测试替身。这是接缝

显然,您不希望所有使用者都显式提供数据上下文(这就是您一开始就拥有原始静态函数的原因)。所以你可以保留这个函数,然后修改它:

    public static void UpdateSchedule(int selectedScheduleId)
    {
        using (var dc = new MyDataContext())
        {
            UpdateScheduleWithDataContext(selectedScheduleId, dc);
        }
    }

如果没有这样的接缝,就不可能单独测试该功能。因此,集成测试将是您所期望的最好结果。

关于c# - 如何对使用数据库访问的静态方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23556830/

相关文章:

c# - 类型转换的性能

python - 如何在 Python 中模拟列表?

ruby-on-rails - 有没有办法测试使用哪种布局呈现 Action Mailer 电子邮件?

javascript - 如何测试传递的函数?

c# - 如何在 NUnit 测试用例中传递字符串和字典?

c# - HttpClient.PostAsync 在 VS 2010 中没有等待

c# - 将 Scenario Outline 与 Specflow 和 Selenium C# 结合使用

unit-testing - 在Go lang中一个接一个地多次模拟具有不同响应的相同功能

java - 何时使用 Mockito.verify()?

unit-testing - Qunit 测试位于包含多个 Controller 的文件中的 ember Controller ?