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 ”字符串而不是“ S OFTWARE \ Autodesk \ AutoCAD ”字符串,则我的测试将失败:该appSets
变量将是null
如果更改字符串大小写(因为该注册表密钥在我的计算机上不存在)。
因此,在这种情况下,测试人员要么需要知道GetAppSets
方法的实现(错误的变体),要么需要处理不区分大小写的字符串之类的参数。
是否可以使用第二种形式?
@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
,因为第一个参数上的参数匹配器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句