NUnit 3.4.1, JustMock 2016.2.713.2
我有要测试的类:
public class AppManager {
public string[] GetAppSets() => Registry.LocalMachine
.OpenSubKey(@"SOFTWAREAutodeskAutoCAD", false)
?.GetSubKeyNames();
}
此外,我有GetAppSets
方法的测试:
[Test]
public void GetAppSets_Returns_ValidValue() {
const string subkey = @"SOFTWAREAutodeskAutoCAD";
/* 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
方法使用"SoftwareAutodeskAutoCAD"或"SoftwareAutodeskAutoCAD"字符串而不是"SOFTWAREAutodeskAutoCAD",则我的测试将失败:appSets
变量将是null
,如果字符串的情况将被改变(因为注册表项不存在于我的计算机上)。
所以,在这种情况下,测试人员需要知道GetAppSets
方法的实现(坏的变体),或处理参数,如不区分大小写的字符串。
有可能使用第二种变体吗?
原问题的答案:
可以使用重载版本的相等断言。
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);
}
@Karolis的回答似乎没有抓住问题的关键。
正确的解决方案是在安排中使用匹配器以不区分大小写的方式匹配键:
var mock = Mock.Create<RegistryKey>();
Mock.Arrange(() => Registry.LocalMachine.OpenSubKey(
Arg.Matches<string>(s => StringComparer.OrdinalIgnoreCase.Equals(s, @"SOFTWAREAutodeskAutoCAD")),
Arg.AnyBool)
).Returns(mock);
var mockKey = Registry.LocalMachine.OpenSubKey(@"softwareautodeskautocad", false);
在上面的mockKey
将是与mock
相同的实例,因为参数匹配器在第一个参数上。