我可以在模拟中处理不区分大小写的字符串吗?

时间:2016-08-09 09:55:25

标签: c# unit-testing testing justmock

NUnit 3.4.1,JustMock 2016.2.713.2

我有正在测试的课程:

public class AppManager {
    public string[] GetAppSets() => Registry.LocalMachine
        .OpenSubKey(@"SOFTWARE\Autodesk\AutoCAD", false)
        ?.GetSubKeyNames();
}

另外,我对GetAppSets方法进行了测试:

[Test]
public void GetAppSets_Returns_ValidValue() {

    const string subkey = @"SOFTWARE\Autodesk\AutoCAD";
    /* The sets of applications which are based on 
     * AutoCAD 2009-2017. */
    string[] fakeSets = new[] { "R17.2", "R18.0",
        "R18.1", "R18.2", "R19.0", "R19.1", "R20.0",
        "R20.1","R21.0" };

    RegistryKey rk = Mock.Create<RegistryKey>();

    Mock.Arrange(() => rk.GetSubKeyNames()).Returns(
        fakeSets);

    Mock.Arrange(() => Registry.LocalMachine.OpenSubKey
    (subkey, false)).Returns(rk);

    AppManager appMng = new AppManager();
    string[] appSets = appMng.GetAppSets();

    Assert.AreEqual(fakeSets, appSets);
}

有效。但是如果GetAppSets方法使用&#34; Software \ Autodesk \ AutoCAD &#34;我的测试将失败。或&#34; software \ autodesk \ autocad &#34;字符串而不是&#34; S OFTWARE \ Autodesk \ AutoCAD &#34;如果字符串大小写将被更改,appSets变量将为null(因为该注册表项我的电脑上不存在。)

所以,在这种情况下, 测试人员需要知道GetAppSets方法实现(错误变体),来处理像这样的参数不区分大小写的字符串。

是否可以使用第二种变体?

2 个答案:

答案 0 :(得分:1)

回答原始问题:

您可以使用重载版本的相等断言。

Assert.AreEqual(fakeSets, appSets, true);

签名:

public static void AreEqual(
string expected,
string actual,
bool ignoreCase)

来源:https://msdn.microsoft.com/en-us/library/ms243448.aspx

回答更新后的问题:

for(int i = 0; i < appSets.Length, i++)
{   // If there is mismatch in length Exception will fail the test.
    Assert.AreEqual(fakeSets[i], appSets[i], true);
}

答案 1 :(得分:0)

似乎@Karolis的答案忽略了问题的关键点。

正确的解决方案是在排列中使用匹配器以不区分大小写的方式匹配密钥:

    var mock = Mock.Create<RegistryKey>();
    Mock.Arrange(() => Registry.LocalMachine.OpenSubKey(
        Arg.Matches<string>(s => StringComparer.OrdinalIgnoreCase.Equals(s, @"SOFTWARE\Autodesk\AutoCAD")),
        Arg.AnyBool)
    ).Returns(mock);


    var mockKey = Registry.LocalMachine.OpenSubKey(@"software\autodesk\autocad", false);

在上面mockKey将是与mock相同的实例,因为第一个参数的参数匹配器。