【问题标题】:Unit Testing Case Statements单元测试用例语句
【发布时间】:2021-11-13 13:26:43
【问题描述】:

我很感激这可能不是问的地方,如果有更好的地方请告诉我。

我有一个旧的存储过程,它选择一些数据并插入到表中。但是,有很多案例语句我想测试,我想知道应该怎么做。

insert into [dbo].[utb_ITP]
...
case when [sme].[Reporting Countries] = 'Multiple Countries'
     then 'United Kingdom-Multiple Countries'
     when patindex('%-$',[sme].[Reporting Countries) > 1
     then left([sme].[Reporting countries], (pat index('%-%', [sme].[Reporting Countries]) - 1 ))
     else [sme].[Reporting Countries]
end as [SVC_COUNTRY]

我认为我看到的样本都是模拟数据和测试函数,但我还没有真正看到像案例陈述这样的例子。我要测试最终输出还是组件?所以我会先测试

[sme].[Reporting Countries] = 'Multiple Countries'
     then 'United Kingdom-Multiple Countries'

我将使用 AssertEqualsTable ,其中预期值为“英国-多个国家”,然后插入实际值将运行案例的第一部分,类似于:

insert into #Expected values ('United Kingdom-Multiple Countries')

insert into #Actual
select case [sme].[Reporting Countries] = 'Multiple Countries'
            then 'United Kingdom-Multiple Countries'
end
from   [SourceTable] as [sme]
where [sme].[Reporting Countries] = 'Multiple Countries'

exec AssertEqualsTable ...

【问题讨论】:

    标签: tdd tsqlt


    【解决方案1】:

    你在正确的轨道上。您确实希望隔离 CASE 语句的这些分支。这意味着您需要为其中的每个可能的分支编写一个测试。

    您还希望将这些测试与其他功能隔离开来。这意味着,伪造所有涉及的表,然后插入足够的行(在这些测试中可能是 1 行)来证明这一点。 tSQLt.FakeTable 允许您仅将数据放入与测试此特定功能相关的列中。在您的情况下,它可能只是 [sme].[Reporting Countries] 列。

    所以你想为'Multiple Countries'编写一个测试,两个测试PATINDEX(例如'value-withdash''othervalue-withdash'),最后一个用于ELSE分支(例如'other value without dash')。

    在测试中,我倾向于更注意确保测试的意图清晰,而不是价值观是否真实。

    如果您在 INSERT 中有其他 case 语句,请按照相同的模式为这些语句编写独立的测试。

    【讨论】:

      猜你喜欢
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多