使用Moq的Verify方法时出错

时间:2012-08-02 15:01:53

标签: c# unit-testing moq

我在单元测试中遇到了Moq的问题,我不确定我哪里出错了。 我的界面中有一个方法,如下所示:

void WriteToRegistryKey (String key, Object value);

我正在对它进行单元测试:

var testRegistry = new Mock<IRegistry>();
testRegistry.Setup(x => x.WriteToRegistryKey(It.IsAny<string>(), It.IsAny<int>()));

Utility testUtility = new ConfigUtil(testRegistry.Object);

testUtility.UpdateRegistry();

testRegistry.Verify(x => x.WriteToRegistryKey("MaxNumLogFiles", 10));

当我调用testUtility.UpdateRegistry()时它会调用我的WriteToRegistryKey我想测试WriteToRegistryKey 传递正确值的方法。

但是,当我运行测试时,我收到了这个:

Moq.MockException : 
Expected invocation on the mock at least once, but was never performed: x => x.WriteToRegistryKey("MaxNumLogFiles", (Object)10)

Configured setups:
x => x.WriteToRegistryKey(It.IsAny<String>(), It.IsAny<Int32>()), Times.Never

Performed invocations:
IRegistry.WriteToRegistryKey("MaxNumLogFiles", 10)

如果我将testRegistry.Verify更改为:

testRegistry.Verify(x => x.WriteToRegistryKey("MaxNumLogFiles", It.IsAny<object>()));

它有效,所以问题似乎是围绕WriteToRegistryKey方法所采用的第二个参数,以及int和object之间的区别,但我似乎无法看 弄明白。

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

查看testUtility.UpdateRegistry(); .WriteToRegistryKey方法的实施主体将会有所帮助。

然而: 我会删除您设置testRegistry模拟的行:
testRegistry.Setup(x => x.WriteToRegistryKey(It.IsAny<string>(), It.IsAny<int>())); 因为,你想要测试它,是否使用正确的参数调用它。没有理由用Moq设置它。

如果你的考试通过了 testRegistry.Verify(x => x.WriteToRegistryKey("MaxNumLogFiles", It.IsAny<object>()));

这可能意味着两件事:

  1. 使用其他 10 值调用WriteToRegistryKey方法 - UpdateRegistry方法中的错误
  2. 或者它为null,因为您使用以下命令设置它:
  3. It.IsAny<string>(), It.IsAny<int>()

    当您使用It.IsAny<type>()时,它也可能是null

相关问题