【问题标题】:Testing method with switch-case using Given-When-Then pattern使用 Given-When-Then 模式的 switch-case 测试方法
【发布时间】:2016-03-12 13:22:47
【问题描述】:

我的旧代码包含的代码看起来有点像这样:

public bool Execute(MyArgument arg)
{
    if(arg.Condition)
    {
        switch(arg.Data)
        {
            case DataValue.A:
            case DataValue.B:
            case DataValue.C:
                return false;   
            case DataValue.F:
            case DataValue.G:
            case DataValue.H:
                return true;
        }
    }
    else
    {
        arg.DoSomeStuff();
        return true;
    }
}

我们正在使用 Given-When-Then 模式,我的问题是我是否应该使用以下测试对其进行测试:

Given NewContext 当执行条件为 True 和 DataValue A Then 返回错误

Given NewContext 当执行条件为 True 和 DataValue B Then 返回错误

Given NewContext 当执行条件为 True 和 DataValue C Then 返回错误

Given NewContext 当执行条件为 True 和 DataValue D Then 返回真

Given NewContext 当执行条件为 True 和 DataValue E Then 返回真

Given NewContext 当执行条件 True 和 DataValue F Then 返回真

在条件为 False 的情况下执行时给定 NewContext 然后 DoSomeStuff 应该调用然后返回true

或者你有什么更好的方法吗? (如果您认为我的测试是有效的,请不要犹豫在 cmets 中这样说)。

【问题讨论】:

  • 感谢您的评论,我们正在使用 NUnit 和 NSubstitute。

标签: c# unit-testing testing legacy-code


【解决方案1】:

我认为你所拥有的一切都很好。就个人而言,我更喜欢冗长而不是更短但不太清楚的东西。至少你在测试什么会很明显。

您也可以考虑利用 NUnit 中的 TestCase 属性。

[Test]
[TestCase(DataValue.A, false)]
[TestCase(DataValue.B, false)]
[TestCase(DataValue.C, false)]
[TestCase(DataValue.F, true)]
[TestCase(DataValue.G, true)]
[TestCase(DataValue.H, true)]
public void GetExpectedValueWhenConditionIsTrue(DataValue argData, bool expectedResult)
{
    var c = new YourClass();
    var arg = new MyArgument { Condition = true, Data = argData };

    var actualResult = c.Execute(arg);

    Assert.AreEqual(expectedResult, actualResult);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多