2

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但如果方法使用“ Software\Autodesk\AutoCAD ”或“ software\autodesk\autocad ”字符串而不是“ SOFTWARE\Autodesk\AutoCAD ”,我的测试将失败:appSets变量将是null如果字符串大小写将更改(因为该注册表密钥在我的计算机上不存在)。

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

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

4

2 回答 2

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);
}
于 2016-08-09T10:06:11.467 回答
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

于 2017-01-20T23:41:54.963 回答